path stringlengths 26 218 | content stringlengths 0 231k |
|---|---|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/filter/PredicateGatedFilter.scala | package com.twitter.home_mixer.functional_component.filter
import com.twitter.product_mixer.core.functional_component.common.alert.Alert
import com.twitter.product_mixer.core.functional_component.filter.Filter
import com.twitter.product_mixer.core.functional_component.filter.FilterResult
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.Conditionally
import com.twitter.product_mixer.core.model.common.UniversalNoun
import com.twitter.product_mixer.core.model.common.identifier.FilterIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
trait FilterPredicate[-Query <: PipelineQuery] {
def apply(query: Query): Boolean
}
/**
* A [[Filter]] with [[Conditionally]] based on a [[FilterPredicate]]
*
* @param predicate the predicate to turn this filter on and off
* @param filter the underlying filter to run when `predicate` is true
* @tparam Query The domain model for the query or request
* @tparam Candidate The type of the candidates
*/
case class PredicateGatedFilter[-Query <: PipelineQuery, Candidate <: UniversalNoun[Any]](
predicate: FilterPredicate[Query],
filter: Filter[Query, Candidate])
extends Filter[Query, Candidate]
with Filter.Conditionally[Query, Candidate] {
override val identifier: FilterIdentifier = FilterIdentifier(
PredicateGatedFilter.IdentifierPrefix + filter.identifier.name)
override val alerts: Seq[Alert] = filter.alerts
override def onlyIf(query: Query, candidates: Seq[CandidateWithFeatures[Candidate]]): Boolean =
Conditionally.and(Filter.Input(query, candidates), filter, predicate(query))
override def apply(
query: Query,
candidates: Seq[CandidateWithFeatures[Candidate]]
): Stitch[FilterResult[Candidate]] = filter.apply(query, candidates)
}
object PredicateGatedFilter {
val IdentifierPrefix = "PredicateGated"
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/filter/PreviouslySeenTweetsFilter.scala | package com.twitter.home_mixer.functional_component.filter
import com.twitter.home_mixer.util.CandidatesUtil
import com.twitter.home_mixer.util.TweetImpressionsHelper
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.functional_component.filter.Filter
import com.twitter.product_mixer.core.functional_component.filter.FilterResult
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.identifier.FilterIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
/**
* Filter out users' previously seen tweets from 2 sources:
* 1. Heron Topology Impression Store in Memcache;
* 2. Manhattan Impression Store;
*/
object PreviouslySeenTweetsFilter extends Filter[PipelineQuery, TweetCandidate] {
override val identifier: FilterIdentifier = FilterIdentifier("PreviouslySeenTweets")
override def apply(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Stitch[FilterResult[TweetCandidate]] = {
val seenTweetIds =
query.features.map(TweetImpressionsHelper.tweetImpressions).getOrElse(Set.empty)
val (removed, kept) = candidates.partition { candidate =>
val tweetIdAndSourceId = CandidatesUtil.getTweetIdAndSourceId(candidate)
tweetIdAndSourceId.exists(seenTweetIds.contains)
}
Stitch.value(FilterResult(kept = kept.map(_.candidate), removed = removed.map(_.candidate)))
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/filter/PreviouslyServedAncestorsFilter.scala | package com.twitter.home_mixer.functional_component.filter
import com.twitter.common_internal.analytics.twitter_client_user_agent_parser.UserAgent
import com.twitter.home_mixer.model.HomeFeatures.IsAncestorCandidateFeature
import com.twitter.home_mixer.model.HomeFeatures.PersistenceEntriesFeature
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.functional_component.filter.Filter
import com.twitter.product_mixer.core.functional_component.filter.FilterResult
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.identifier.FilterIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
import com.twitter.timelinemixer.injection.store.persistence.TimelinePersistenceUtils
import com.twitter.timelines.util.client_info.ClientPlatform
object PreviouslyServedAncestorsFilter
extends Filter[PipelineQuery, TweetCandidate]
with TimelinePersistenceUtils {
override val identifier: FilterIdentifier = FilterIdentifier("PreviouslyServedAncestors")
override def apply(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Stitch[FilterResult[TweetCandidate]] = {
val clientPlatform = ClientPlatform.fromQueryOptions(
clientAppId = query.clientContext.appId,
userAgent = query.clientContext.userAgent.flatMap(UserAgent.fromString))
val entries =
query.features.map(_.getOrElse(PersistenceEntriesFeature, Seq.empty)).toSeq.flatten
val tweetIds = applicableResponses(clientPlatform, entries)
.flatMap(_.entries.flatMap(_.tweetIds(includeSourceTweets = true))).toSet
val ancestorIds =
candidates
.filter(_.features.getOrElse(IsAncestorCandidateFeature, false)).map(_.candidate.id).toSet
val (removed, kept) =
candidates
.map(_.candidate).partition(candidate =>
tweetIds.contains(candidate.id) && ancestorIds.contains(candidate.id))
Stitch.value(FilterResult(kept = kept, removed = removed))
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/filter/PreviouslyServedTweetPreviewsFilter.scala | package com.twitter.home_mixer.functional_component.filter
import com.twitter.home_mixer.model.HomeFeatures.ServedTweetPreviewIdsFeature
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.functional_component.filter.Filter
import com.twitter.product_mixer.core.functional_component.filter.FilterResult
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.identifier.FilterIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
object PreviouslyServedTweetPreviewsFilter extends Filter[PipelineQuery, TweetCandidate] {
override val identifier: FilterIdentifier = FilterIdentifier("PreviouslyServedTweetPreviews")
override def apply(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Stitch[FilterResult[TweetCandidate]] = {
val servedTweetPreviewIds =
query.features.map(_.getOrElse(ServedTweetPreviewIdsFeature, Seq.empty)).toSeq.flatten.toSet
val (removed, kept) = candidates.partition { candidate =>
servedTweetPreviewIds.contains(candidate.candidate.id)
}
Stitch.value(FilterResult(kept = kept.map(_.candidate), removed = removed.map(_.candidate)))
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/filter/PreviouslyServedTweetsFilter.scala | package com.twitter.home_mixer.functional_component.filter
import com.twitter.home_mixer.model.HomeFeatures.GetOlderFeature
import com.twitter.home_mixer.model.HomeFeatures.ServedTweetIdsFeature
import com.twitter.home_mixer.util.CandidatesUtil
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.functional_component.filter.Filter
import com.twitter.product_mixer.core.functional_component.filter.FilterResult
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.identifier.FilterIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
object PreviouslyServedTweetsFilter
extends Filter[PipelineQuery, TweetCandidate]
with Filter.Conditionally[PipelineQuery, TweetCandidate] {
override val identifier: FilterIdentifier = FilterIdentifier("PreviouslyServedTweets")
override def onlyIf(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Boolean = {
query.features.exists(_.getOrElse(GetOlderFeature, false))
}
override def apply(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Stitch[FilterResult[TweetCandidate]] = {
val servedTweetIds =
query.features.map(_.getOrElse(ServedTweetIdsFeature, Seq.empty)).toSeq.flatten.toSet
val (removed, kept) = candidates.partition { candidate =>
val tweetIdAndSourceId = CandidatesUtil.getTweetIdAndSourceId(candidate)
tweetIdAndSourceId.exists(servedTweetIds.contains)
}
Stitch.value(FilterResult(kept = kept.map(_.candidate), removed = removed.map(_.candidate)))
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/filter/RejectTweetFromViewerFilter.scala | package com.twitter.home_mixer.functional_component.filter
import com.twitter.home_mixer.util.CandidatesUtil
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.functional_component.filter.Filter
import com.twitter.product_mixer.core.functional_component.filter.FilterResult
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.identifier.FilterIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
object RejectTweetFromViewerFilter extends Filter[PipelineQuery, TweetCandidate] {
override val identifier: FilterIdentifier = FilterIdentifier("RejectTweetFromViewer")
override def apply(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Stitch[FilterResult[TweetCandidate]] = {
val (removed, kept) = candidates.partition(candidate =>
CandidatesUtil.isAuthoredByViewer(query, candidate.features))
Stitch.value(FilterResult(kept = kept.map(_.candidate), removed = removed.map(_.candidate)))
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/filter/ReplyFilter.scala | package com.twitter.home_mixer.functional_component.filter
import com.twitter.home_mixer.model.HomeFeatures.InReplyToTweetIdFeature
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.functional_component.filter.Filter
import com.twitter.product_mixer.core.functional_component.filter.FilterResult
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.identifier.FilterIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
object ReplyFilter extends Filter[PipelineQuery, TweetCandidate] {
override val identifier: FilterIdentifier = FilterIdentifier("Reply")
override def apply(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Stitch[FilterResult[TweetCandidate]] = {
val (kept, removed) = candidates
.partition { candidate =>
candidate.features.getOrElse(InReplyToTweetIdFeature, None).isEmpty
}
val filterResult = FilterResult(
kept = kept.map(_.candidate),
removed = removed.map(_.candidate)
)
Stitch.value(filterResult)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/filter/RetweetDeduplicationFilter.scala | package com.twitter.home_mixer.functional_component.filter
import com.twitter.home_mixer.model.HomeFeatures.IsRetweetFeature
import com.twitter.home_mixer.util.CandidatesUtil
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.functional_component.filter.Filter
import com.twitter.product_mixer.core.functional_component.filter.FilterResult
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.identifier.FilterIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
import scala.collection.mutable
object RetweetDeduplicationFilter extends Filter[PipelineQuery, TweetCandidate] {
override val identifier: FilterIdentifier = FilterIdentifier("RetweetDeduplication")
override def apply(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Stitch[FilterResult[TweetCandidate]] = {
// If there are 2 retweets of the same native tweet, we will choose the first one
// The tweets are returned in descending score order, so we will choose the higher scored tweet
val dedupedTweetIdsSet =
candidates.partition(_.features.getOrElse(IsRetweetFeature, false)) match {
case (retweets, nativeTweets) =>
val nativeTweetIds = nativeTweets.map(_.candidate.id)
val seenTweetIds = mutable.Set[Long]() ++ nativeTweetIds
val dedupedRetweets = retweets.filter { retweet =>
val tweetIdAndSourceId = CandidatesUtil.getTweetIdAndSourceId(retweet)
val retweetIsUnique = tweetIdAndSourceId.forall(!seenTweetIds.contains(_))
if (retweetIsUnique) {
seenTweetIds ++= tweetIdAndSourceId
}
retweetIsUnique
}
(nativeTweets ++ dedupedRetweets).map(_.candidate.id).toSet
}
val (kept, removed) =
candidates
.map(_.candidate).partition(candidate => dedupedTweetIdsSet.contains(candidate.id))
Stitch.value(FilterResult(kept = kept, removed = removed))
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/filter/RetweetFilter.scala | package com.twitter.home_mixer.functional_component.filter
import com.twitter.home_mixer.model.HomeFeatures.IsRetweetFeature
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.functional_component.filter.Filter
import com.twitter.product_mixer.core.functional_component.filter.FilterResult
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.identifier.FilterIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
object RetweetFilter extends Filter[PipelineQuery, TweetCandidate] {
override val identifier: FilterIdentifier = FilterIdentifier("Retweet")
override def apply(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Stitch[FilterResult[TweetCandidate]] = {
val (kept, removed) = candidates
.partition { candidate =>
!candidate.features.getOrElse(IsRetweetFeature, false)
}
val filterResult = FilterResult(
kept = kept.map(_.candidate),
removed = removed.map(_.candidate)
)
Stitch.value(filterResult)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/gate/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"configapi/configapi-core/src/main/scala/com/twitter/timelines/configapi",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/feature_hydrator",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/util",
"home-mixer/thrift/src/main/thrift:thrift-scala",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/functional_component/common",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/functional_component/gate",
"src/thrift/com/twitter/gizmoduck:thrift-scala",
"stitch/stitch-socialgraph",
"timelinemixer/server/src/main/scala/com/twitter/timelinemixer/injection/store/persistence",
"timelineservice/common/src/main/scala/com/twitter/timelineservice/model",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/gate/DismissFatigueGate.scala | package com.twitter.home_mixer.functional_component.gate
import com.twitter.conversions.DurationOps._
import com.twitter.product_mixer.core.feature.Feature
import com.twitter.product_mixer.core.functional_component.gate.Gate
import com.twitter.product_mixer.core.model.common.identifier.GateIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
import com.twitter.timelinemixer.clients.manhattan.DismissInfo
import com.twitter.timelineservice.suggests.thriftscala.SuggestType
import com.twitter.util.Duration
object DismissFatigueGate {
// how long a dismiss action from user needs to be respected
val DefaultBaseDismissDuration = 7.days
val MaximumDismissalCountMultiplier = 4
}
case class DismissFatigueGate(
suggestType: SuggestType,
dismissInfoFeature: Feature[PipelineQuery, Map[SuggestType, Option[DismissInfo]]],
baseDismissDuration: Duration = DismissFatigueGate.DefaultBaseDismissDuration,
) extends Gate[PipelineQuery] {
override val identifier: GateIdentifier = GateIdentifier("DismissFatigue")
override def shouldContinue(query: PipelineQuery): Stitch[Boolean] = {
val dismissInfoMap = query.features.map(
_.getOrElse(dismissInfoFeature, Map.empty[SuggestType, Option[DismissInfo]]))
val isVisible = dismissInfoMap
.flatMap(_.get(suggestType))
.flatMap(_.map { info =>
val currentDismissalDuration = query.queryTime.since(info.lastDismissed)
val targetDismissalDuration = dismissDurationForCount(info.count, baseDismissDuration)
currentDismissalDuration > targetDismissalDuration
}).getOrElse(true)
Stitch.value(isVisible)
}
private def dismissDurationForCount(
dismissCount: Int,
dismissDuration: Duration
): Duration =
// limit to maximum dismissal duration
dismissDuration * Math.min(dismissCount, DismissFatigueGate.MaximumDismissalCountMultiplier)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/gate/ExcludeSoftUserGate.scala | package com.twitter.home_mixer.functional_component.gate
import com.twitter.gizmoduck.{thriftscala => t}
import com.twitter.home_mixer.model.HomeFeatures.UserTypeFeature
import com.twitter.product_mixer.core.functional_component.gate.Gate
import com.twitter.product_mixer.core.model.common.identifier.GateIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
/**
* A Soft User is a user who is in the gradual onboarding state. This gate can be
* used to turn off certain functionality like ads for these users.
*/
object ExcludeSoftUserGate extends Gate[PipelineQuery] {
override val identifier: GateIdentifier = GateIdentifier("ExcludeSoftUser")
override def shouldContinue(query: PipelineQuery): Stitch[Boolean] = {
val softUser = query.features
.exists(_.getOrElse(UserTypeFeature, None).exists(_ == t.UserType.Soft))
Stitch.value(!softUser)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/gate/RequestContextGate.scala | package com.twitter.home_mixer.functional_component.gate
import com.twitter.home_mixer.model.request.DeviceContext.RequestContext
import com.twitter.home_mixer.model.request.HasDeviceContext
import com.twitter.product_mixer.core.functional_component.gate.Gate
import com.twitter.product_mixer.core.model.common.identifier.GateIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
/**
* Gate that fetches the request context from the device context and
* continues if the request context matches *any* of the specified ones.
*/
case class RequestContextGate(requestContexts: Seq[RequestContext.Value])
extends Gate[PipelineQuery with HasDeviceContext] {
override val identifier: GateIdentifier = GateIdentifier("RequestContext")
override def shouldContinue(query: PipelineQuery with HasDeviceContext): Stitch[Boolean] =
Stitch.value(
requestContexts.exists(query.deviceContext.flatMap(_.requestContextValue).contains))
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/gate/RequestContextNotGate.scala | package com.twitter.home_mixer.functional_component.gate
import com.twitter.home_mixer.model.request.DeviceContext.RequestContext
import com.twitter.home_mixer.model.request.HasDeviceContext
import com.twitter.product_mixer.core.functional_component.gate.Gate
import com.twitter.product_mixer.core.model.common.identifier.GateIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
/**
* Gate that fetches the request context from the device context and
* continues if the request context does not match any of the specified ones.
*
* If no input request context is specified, the gate continues
*/
case class RequestContextNotGate(requestContexts: Seq[RequestContext.Value])
extends Gate[PipelineQuery with HasDeviceContext] {
override val identifier: GateIdentifier = GateIdentifier("RequestContextNot")
override def shouldContinue(query: PipelineQuery with HasDeviceContext): Stitch[Boolean] =
Stitch.value(
!requestContexts.exists(query.deviceContext.flatMap(_.requestContextValue).contains))
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/gate/SupportedLanguagesGate.scala | package com.twitter.home_mixer.functional_component.gate
import com.twitter.product_mixer.core.functional_component.gate.Gate
import com.twitter.product_mixer.core.model.common.identifier.GateIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
object SupportedLanguagesGate extends Gate[PipelineQuery] {
override val identifier: GateIdentifier = GateIdentifier("SupportedLanguages")
// Production languages which have high translation coverage for strings used in Home Timeline.
private val supportedLanguages: Set[String] = Set(
"ar", // Arabic
"ar-x-fm", // Arabic (Female)
"bg", // Bulgarian
"bn", // Bengali
"ca", // Catalan
"cs", // Czech
"da", // Danish
"de", // German
"el", // Greek
"en", // English
"en-gb", // British English
"en-ss", // English Screen shot
"en-xx", // English Pseudo
"es", // Spanish
"eu", // Basque
"fa", // Farsi (Persian)
"fi", // Finnish
"fil", // Filipino
"fr", // French
"ga", // Irish
"gl", // Galician
"gu", // Gujarati
"he", // Hebrew
"hi", // Hindi
"hr", // Croatian
"hu", // Hungarian
"id", // Indonesian
"it", // Italian
"ja", // Japanese
"kn", // Kannada
"ko", // Korean
"mr", // Marathi
"msa", // Malay
"nl", // Dutch
"no", // Norwegian
"pl", // Polish
"pt", // Portuguese
"ro", // Romanian
"ru", // Russian
"sk", // Slovak
"sr", // Serbian
"sv", // Swedish
"ta", // Tamil
"th", // Thai
"tr", // Turkish
"uk", // Ukrainian
"ur", // Urdu
"vi", // Vietnamese
"zh-cn", // Simplified Chinese
"zh-tw" // Traditional Chinese
)
override def shouldContinue(query: PipelineQuery): Stitch[Boolean] =
Stitch.value(query.getLanguageCode.forall(supportedLanguages.contains))
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/gate/TimelinesPersistenceStoreLastInjectionGate.scala | package com.twitter.home_mixer.functional_component.gate
import com.twitter.common_internal.analytics.twitter_client_user_agent_parser.UserAgent
import com.twitter.product_mixer.core.feature.Feature
import com.twitter.product_mixer.core.functional_component.gate.Gate
import com.twitter.product_mixer.core.model.common.identifier.GateIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
import com.twitter.timelinemixer.clients.persistence.TimelineResponseV3
import com.twitter.timelinemixer.injection.store.persistence.TimelinePersistenceUtils
import com.twitter.timelines.configapi.Param
import com.twitter.timelines.util.client_info.ClientPlatform
import com.twitter.timelineservice.model.rich.EntityIdType
import com.twitter.util.Duration
import com.twitter.util.Time
/**
* Gate used to reduce the frequency of injections. Note that the actual interval between injections may be
* less than the specified minInjectionIntervalParam if data is unavailable or missing. For example, being deleted by
* the persistence store via a TTL or similar mechanism.
*
* @param minInjectionIntervalParam the desired minimum interval between injections
* @param persistenceEntriesFeature the feature for retrieving persisted timeline responses
*/
case class TimelinesPersistenceStoreLastInjectionGate(
minInjectionIntervalParam: Param[Duration],
persistenceEntriesFeature: Feature[PipelineQuery, Seq[TimelineResponseV3]],
entityIdType: EntityIdType.Value)
extends Gate[PipelineQuery]
with TimelinePersistenceUtils {
override val identifier: GateIdentifier = GateIdentifier("TimelinesPersistenceStoreLastInjection")
override def shouldContinue(query: PipelineQuery): Stitch[Boolean] =
Stitch(
query.queryTime.since(getLastInjectionTime(query)) > query.params(minInjectionIntervalParam))
private def getLastInjectionTime(query: PipelineQuery) = query.features
.flatMap { featureMap =>
val timelineResponses = featureMap.getOrElse(persistenceEntriesFeature, Seq.empty)
val clientPlatform = ClientPlatform.fromQueryOptions(
clientAppId = query.clientContext.appId,
userAgent = query.clientContext.userAgent.flatMap(UserAgent.fromString)
)
val sortedResponses = responseByClient(clientPlatform, timelineResponses)
val latestResponseWithEntityIdTypeEntry =
sortedResponses.find(_.entries.exists(_.entityIdType == entityIdType))
latestResponseWithEntityIdTypeEntry.map(_.servedTime)
}.getOrElse(Time.Bottom)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/query_transformer/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"common-internal/analytics/twitter-client-user-agent-parser/src/main/scala",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/functional_component/transformer",
"timelinemixer/server/src/main/scala/com/twitter/timelinemixer/injection/store/persistence",
"timelineservice/common:model",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/query_transformer/EditedTweetsCandidatePipelineQueryTransformer.scala | package com.twitter.home_mixer.functional_component.query_transformer
import com.twitter.common_internal.analytics.twitter_client_user_agent_parser.UserAgent
import com.twitter.conversions.DurationOps._
import com.twitter.home_mixer.model.HomeFeatures.PersistenceEntriesFeature
import com.twitter.product_mixer.core.feature.featuremap.FeatureMap
import com.twitter.product_mixer.core.functional_component.transformer.CandidatePipelineQueryTransformer
import com.twitter.product_mixer.core.model.common.identifier.TransformerIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.timelinemixer.clients.persistence.EntryWithItemIds
import com.twitter.timelines.persistence.thriftscala.RequestType
import com.twitter.timelines.util.client_info.ClientPlatform
import com.twitter.timelineservice.model.rich.EntityIdType
import com.twitter.util.Time
object EditedTweetsCandidatePipelineQueryTransformer
extends CandidatePipelineQueryTransformer[PipelineQuery, Seq[Long]] {
override val identifier: TransformerIdentifier = TransformerIdentifier("EditedTweets")
// The time window for which a tweet remains editable after creation.
private val EditTimeWindow = 60.minutes
override def transform(query: PipelineQuery): Seq[Long] = {
val applicableCandidates = getApplicableCandidates(query)
if (applicableCandidates.nonEmpty) {
// Include the response corresponding with the Previous Timeline Load (PTL).
// Any tweets in it could have become stale since being served.
val previousTimelineLoadTime = applicableCandidates.head.servedTime
// The time window for editing a tweet is 60 minutes,
// so we ignore responses older than (PTL Time - 60 mins).
val inWindowCandidates: Seq[PersistenceStoreEntry] = applicableCandidates
.takeWhile(_.servedTime.until(previousTimelineLoadTime) < EditTimeWindow)
// Exclude the tweet IDs for which ReplaceEntry instructions have already been sent.
val (tweetsAlreadyReplaced, tweetsToCheck) = inWindowCandidates
.partition(_.entryWithItemIds.itemIds.exists(_.head.entryIdToReplace.nonEmpty))
val tweetIdFromEntry: PartialFunction[PersistenceStoreEntry, Long] = {
case entry if entry.tweetId.nonEmpty => entry.tweetId.get
}
val tweetIdsAlreadyReplaced: Set[Long] = tweetsAlreadyReplaced.collect(tweetIdFromEntry).toSet
val tweetIdsToCheck: Seq[Long] = tweetsToCheck.collect(tweetIdFromEntry)
tweetIdsToCheck.filterNot(tweetIdsAlreadyReplaced.contains).distinct
} else Seq.empty
}
// The candidates here come from the Timelines Persistence Store, via a query feature
private def getApplicableCandidates(query: PipelineQuery): Seq[PersistenceStoreEntry] = {
val userAgent = UserAgent.fromString(query.clientContext.userAgent.getOrElse(""))
val clientPlatform = ClientPlatform.fromQueryOptions(query.clientContext.appId, userAgent)
val sortedResponses = query.features
.getOrElse(FeatureMap.empty)
.getOrElse(PersistenceEntriesFeature, Seq.empty)
.filter(_.clientPlatform == clientPlatform)
.sortBy(-_.servedTime.inMilliseconds)
val recentResponses = sortedResponses.indexWhere(_.requestType == RequestType.Initial) match {
case -1 => sortedResponses
case lastGetInitialIndex => sortedResponses.take(lastGetInitialIndex + 1)
}
recentResponses.flatMap { r =>
r.entries.collect {
case entry if entry.entityIdType == EntityIdType.Tweet =>
PersistenceStoreEntry(entry, r.servedTime, r.clientPlatform, r.requestType)
}
}.distinct
}
}
case class PersistenceStoreEntry(
entryWithItemIds: EntryWithItemIds,
servedTime: Time,
clientPlatform: ClientPlatform,
requestType: RequestType) {
// Timelines Persistence Store currently includes 1 tweet ID per entryWithItemIds for tweets
val tweetId: Option[Long] = entryWithItemIds.itemIds.flatMap(_.head.tweetId)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/scorer/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
dependencies = [
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/param",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/util",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/pipeline",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/product",
"src/thrift/com/twitter/timelines/common:thrift-scala",
"src/thrift/com/twitter/timelineservice/server/internal:thrift-scala",
"timelineservice/common:model",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/scorer/FeedbackFatigueScorer.scala | package com.twitter.home_mixer.functional_component.scorer
import com.twitter.conversions.DurationOps._
import com.twitter.home_mixer.model.HomeFeatures.AuthorIdFeature
import com.twitter.home_mixer.model.HomeFeatures.FeedbackHistoryFeature
import com.twitter.home_mixer.model.HomeFeatures.IsRetweetFeature
import com.twitter.home_mixer.model.HomeFeatures.SGSValidFollowedByUserIdsFeature
import com.twitter.home_mixer.model.HomeFeatures.SGSValidLikedByUserIdsFeature
import com.twitter.home_mixer.model.HomeFeatures.ScoreFeature
import com.twitter.home_mixer.util.CandidatesUtil
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.feature.Feature
import com.twitter.product_mixer.core.feature.featuremap.FeatureMap
import com.twitter.product_mixer.core.feature.featuremap.FeatureMapBuilder
import com.twitter.product_mixer.core.functional_component.scorer.Scorer
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.Conditionally
import com.twitter.product_mixer.core.model.common.identifier.ScorerIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
import com.twitter.timelines.common.{thriftscala => tl}
import com.twitter.timelineservice.model.FeedbackEntry
import com.twitter.timelineservice.{thriftscala => tls}
import com.twitter.util.Time
import scala.collection.mutable
object FeedbackFatigueScorer
extends Scorer[PipelineQuery, TweetCandidate]
with Conditionally[PipelineQuery] {
override val identifier: ScorerIdentifier = ScorerIdentifier("FeedbackFatigue")
override def features: Set[Feature[_, _]] = Set(ScoreFeature)
override def onlyIf(query: PipelineQuery): Boolean =
query.features.exists(_.getOrElse(FeedbackHistoryFeature, Seq.empty).nonEmpty)
val DurationForFiltering = 14.days
val DurationForDiscounting = 140.days
private val ScoreMultiplierLowerBound = 0.2
private val ScoreMultiplierUpperBound = 1.0
private val ScoreMultiplierIncrementsCount = 4
private val ScoreMultiplierIncrement =
(ScoreMultiplierUpperBound - ScoreMultiplierLowerBound) / ScoreMultiplierIncrementsCount
private val ScoreMultiplierIncrementDurationInDays =
DurationForDiscounting.inDays / ScoreMultiplierIncrementsCount.toDouble
override def apply(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Stitch[Seq[FeatureMap]] = {
val feedbackEntriesByEngagementType =
query.features
.getOrElse(FeatureMap.empty).getOrElse(FeedbackHistoryFeature, Seq.empty)
.filter { entry =>
val timeSinceFeedback = query.queryTime.minus(entry.timestamp)
timeSinceFeedback < DurationForFiltering + DurationForDiscounting &&
entry.feedbackType == tls.FeedbackType.SeeFewer
}.groupBy(_.engagementType)
val authorsToDiscount =
getUserDiscounts(
query.queryTime,
feedbackEntriesByEngagementType.getOrElse(tls.FeedbackEngagementType.Tweet, Seq.empty))
val likersToDiscount =
getUserDiscounts(
query.queryTime,
feedbackEntriesByEngagementType.getOrElse(tls.FeedbackEngagementType.Like, Seq.empty))
val followersToDiscount =
getUserDiscounts(
query.queryTime,
feedbackEntriesByEngagementType.getOrElse(tls.FeedbackEngagementType.Follow, Seq.empty))
val retweetersToDiscount =
getUserDiscounts(
query.queryTime,
feedbackEntriesByEngagementType.getOrElse(tls.FeedbackEngagementType.Retweet, Seq.empty))
val featureMaps = candidates.map { candidate =>
val multiplier = getScoreMultiplier(
candidate,
authorsToDiscount,
likersToDiscount,
followersToDiscount,
retweetersToDiscount
)
val score = candidate.features.getOrElse(ScoreFeature, None)
FeatureMapBuilder().add(ScoreFeature, score.map(_ * multiplier)).build()
}
Stitch.value(featureMaps)
}
def getScoreMultiplier(
candidate: CandidateWithFeatures[TweetCandidate],
authorsToDiscount: Map[Long, Double],
likersToDiscount: Map[Long, Double],
followersToDiscount: Map[Long, Double],
retweetersToDiscount: Map[Long, Double],
): Double = {
val originalAuthorId =
CandidatesUtil.getOriginalAuthorId(candidate.features).getOrElse(0L)
val originalAuthorMultiplier = authorsToDiscount.getOrElse(originalAuthorId, 1.0)
val likers = candidate.features.getOrElse(SGSValidLikedByUserIdsFeature, Seq.empty)
val likerMultipliers = likers.flatMap(likersToDiscount.get)
val likerMultiplier =
if (likerMultipliers.nonEmpty && likers.size == likerMultipliers.size)
likerMultipliers.max
else 1.0
val followers = candidate.features.getOrElse(SGSValidFollowedByUserIdsFeature, Seq.empty)
val followerMultipliers = followers.flatMap(followersToDiscount.get)
val followerMultiplier =
if (followerMultipliers.nonEmpty && followers.size == followerMultipliers.size &&
likers.isEmpty)
followerMultipliers.max
else 1.0
val authorId = candidate.features.getOrElse(AuthorIdFeature, None).getOrElse(0L)
val retweeterMultiplier =
if (candidate.features.getOrElse(IsRetweetFeature, false))
retweetersToDiscount.getOrElse(authorId, 1.0)
else 1.0
originalAuthorMultiplier * likerMultiplier * followerMultiplier * retweeterMultiplier
}
def getUserDiscounts(
queryTime: Time,
feedbackEntries: Seq[FeedbackEntry],
): Map[Long, Double] = {
val userDiscounts = mutable.Map[Long, Double]()
feedbackEntries
.collect {
case FeedbackEntry(_, _, tl.FeedbackEntity.UserId(userId), timestamp, _) =>
val timeSinceFeedback = queryTime.minus(timestamp)
val timeSinceDiscounting = timeSinceFeedback - DurationForFiltering
val multiplier = ((timeSinceDiscounting.inDays / ScoreMultiplierIncrementDurationInDays)
* ScoreMultiplierIncrement + ScoreMultiplierLowerBound)
userDiscounts.update(userId, multiplier)
}
userDiscounts.toMap
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/scorer/OONTweetScalingScorer.scala | package com.twitter.home_mixer.functional_component.scorer
import com.twitter.home_mixer.model.HomeFeatures.InNetworkFeature
import com.twitter.home_mixer.model.HomeFeatures.IsRetweetFeature
import com.twitter.home_mixer.model.HomeFeatures.ScoreFeature
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.feature.Feature
import com.twitter.product_mixer.core.feature.featuremap.FeatureMap
import com.twitter.product_mixer.core.feature.featuremap.FeatureMapBuilder
import com.twitter.product_mixer.core.functional_component.scorer.Scorer
import com.twitter.product_mixer.core.model.common.CandidateWithFeatures
import com.twitter.product_mixer.core.model.common.identifier.ScorerIdentifier
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
/**
* Scales scores of each out-of-network tweet by the specified scale factor
*/
object OONTweetScalingScorer extends Scorer[PipelineQuery, TweetCandidate] {
override val identifier: ScorerIdentifier = ScorerIdentifier("OONTweetScaling")
override val features: Set[Feature[_, _]] = Set(ScoreFeature)
private val ScaleFactor = 0.75
override def apply(
query: PipelineQuery,
candidates: Seq[CandidateWithFeatures[TweetCandidate]]
): Stitch[Seq[FeatureMap]] = {
Stitch.value {
candidates.map { candidate =>
val score = candidate.features.getOrElse(ScoreFeature, None)
val updatedScore = if (selector(candidate)) score.map(_ * ScaleFactor) else score
FeatureMapBuilder().add(ScoreFeature, updatedScore).build()
}
}
}
/**
* We should only be applying this multiplier to Out-Of-Network tweets.
* In-Network Retweets of Out-Of-Network tweets should not have this multiplier applied
*/
private def selector(candidate: CandidateWithFeatures[TweetCandidate]): Boolean = {
!candidate.features.getOrElse(InNetworkFeature, false) &&
!candidate.features.getOrElse(IsRetweetFeature, false)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/selector/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/decorator",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/decorator/builder",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/param",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/util",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/model/candidate",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/model/presentation/urt",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/functional_component/decorator/urt/builder",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/functional_component/selector",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/common/identifier",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/common/presentation",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/marshalling/response/urt/item",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/pipeline",
"src/scala/com/twitter/suggests/controller_data",
"stringcenter/client",
"stringcenter/client/src/main/java",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/selector/DebunchCandidates.scala | package com.twitter.home_mixer.functional_component.selector
import com.twitter.home_mixer.functional_component.selector.DebunchCandidates.TrailingTweetsMinSize
import com.twitter.home_mixer.functional_component.selector.DebunchCandidates.TrailingTweetsPortionToKeep
import com.twitter.home_mixer.model.HomeFeatures.GetNewerFeature
import com.twitter.product_mixer.core.functional_component.common.CandidateScope
import com.twitter.product_mixer.core.functional_component.common.CandidateScope.PartitionedCandidates
import com.twitter.product_mixer.core.functional_component.selector.Selector
import com.twitter.product_mixer.core.functional_component.selector.SelectorResult
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.pipeline.PipelineQuery
trait MustDebunch {
def apply(candidate: CandidateWithDetails): Boolean
}
object DebunchCandidates {
val TrailingTweetsMinSize = 5
val TrailingTweetsPortionToKeep = 0.1
}
/**
* This selector rearranges the candidates to only allow bunches of size [[maxBunchSize]], where a
* bunch is a consecutive sequence of candidates that meet [[mustDebunch]].
*/
case class DebunchCandidates(
override val pipelineScope: CandidateScope,
mustDebunch: MustDebunch,
maxBunchSize: Int)
extends Selector[PipelineQuery] {
override def apply(
query: PipelineQuery,
remainingCandidates: Seq[CandidateWithDetails],
result: Seq[CandidateWithDetails]
): SelectorResult = {
val PartitionedCandidates(selectedCandidates, otherCandidates) =
pipelineScope.partition(remainingCandidates)
val mutableCandidates = collection.mutable.ListBuffer(selectedCandidates: _*)
var candidatePointer = 0
var nonDebunchPointer = 0
var bunchSize = 0
var finalNonDebunch = -1
while (candidatePointer < mutableCandidates.size) {
if (mustDebunch(mutableCandidates(candidatePointer))) bunchSize += 1
else {
bunchSize = 0
finalNonDebunch = candidatePointer
}
if (bunchSize > maxBunchSize) {
nonDebunchPointer = Math.max(candidatePointer, nonDebunchPointer)
while (nonDebunchPointer < mutableCandidates.size &&
mustDebunch(mutableCandidates(nonDebunchPointer))) {
nonDebunchPointer += 1
}
if (nonDebunchPointer == mutableCandidates.size)
candidatePointer = mutableCandidates.size
else {
val nextNonDebunch = mutableCandidates(nonDebunchPointer)
mutableCandidates.remove(nonDebunchPointer)
mutableCandidates.insert(candidatePointer, nextNonDebunch)
bunchSize = 0
finalNonDebunch = candidatePointer
}
}
candidatePointer += 1
}
val debunchedCandidates = if (query.features.exists(_.getOrElse(GetNewerFeature, false))) {
val trailingTweetsSize = mutableCandidates.size - finalNonDebunch - 1
val keepCandidates = finalNonDebunch + 1 +
Math.max(TrailingTweetsMinSize, TrailingTweetsPortionToKeep * trailingTweetsSize).toInt
mutableCandidates.toList.take(keepCandidates)
} else mutableCandidates.toList
val updatedCandidates = otherCandidates ++ debunchedCandidates
SelectorResult(remainingCandidates = updatedCandidates, result = result)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/selector/UpdateConversationModuleId.scala | package com.twitter.home_mixer.functional_component.selector
import com.twitter.product_mixer.component_library.model.presentation.urt.UrtModulePresentation
import com.twitter.product_mixer.core.functional_component.common.CandidateScope
import com.twitter.product_mixer.core.functional_component.common.CandidateScope.PartitionedCandidates
import com.twitter.product_mixer.core.functional_component.selector.Selector
import com.twitter.product_mixer.core.functional_component.selector.SelectorResult
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.model.common.presentation.ModuleCandidateWithDetails
import com.twitter.product_mixer.core.pipeline.PipelineQuery
/**
* This selector updates the id of the conversation modules to be the head of the module's id.
*/
case class UpdateConversationModuleId(
override val pipelineScope: CandidateScope)
extends Selector[PipelineQuery] {
override def apply(
query: PipelineQuery,
remainingCandidates: Seq[CandidateWithDetails],
result: Seq[CandidateWithDetails]
): SelectorResult = {
val PartitionedCandidates(selectedCandidates, otherCandidates) =
pipelineScope.partition(remainingCandidates)
val updatedCandidates = selectedCandidates.map {
case module @ ModuleCandidateWithDetails(candidates, presentationOpt, _) =>
val updatedPresentation = presentationOpt.map {
case urtModule @ UrtModulePresentation(timelineModule) =>
urtModule.copy(timelineModule =
timelineModule.copy(id = candidates.head.candidateIdLong))
}
module.copy(presentation = updatedPresentation)
case candidate => candidate
}
SelectorResult(remainingCandidates = updatedCandidates ++ otherCandidates, result = result)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/selector/UpdateHomeClientEventDetails.scala | package com.twitter.home_mixer.functional_component.selector
import com.twitter.home_mixer.functional_component.decorator.builder.HomeClientEventDetailsBuilder
import com.twitter.home_mixer.model.HomeFeatures.AncestorsFeature
import com.twitter.home_mixer.model.HomeFeatures.ConversationModule2DisplayedTweetsFeature
import com.twitter.home_mixer.model.HomeFeatures.ConversationModuleHasGapFeature
import com.twitter.home_mixer.model.HomeFeatures.HasRandomTweetFeature
import com.twitter.home_mixer.model.HomeFeatures.IsRandomTweetAboveFeature
import com.twitter.home_mixer.model.HomeFeatures.IsRandomTweetFeature
import com.twitter.home_mixer.model.HomeFeatures.PositionFeature
import com.twitter.home_mixer.model.HomeFeatures.ServedInConversationModuleFeature
import com.twitter.home_mixer.model.HomeFeatures.ServedSizeFeature
import com.twitter.product_mixer.component_library.model.presentation.urt.UrtItemPresentation
import com.twitter.product_mixer.component_library.model.presentation.urt.UrtModulePresentation
import com.twitter.product_mixer.core.feature.featuremap.FeatureMap
import com.twitter.product_mixer.core.feature.featuremap.FeatureMapBuilder
import com.twitter.product_mixer.core.functional_component.common.CandidateScope
import com.twitter.product_mixer.core.functional_component.common.SpecificPipelines
import com.twitter.product_mixer.core.functional_component.selector.Selector
import com.twitter.product_mixer.core.functional_component.selector.SelectorResult
import com.twitter.product_mixer.core.model.common.identifier.CandidatePipelineIdentifier
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.model.common.presentation.ItemCandidateWithDetails
import com.twitter.product_mixer.core.model.common.presentation.ModuleCandidateWithDetails
import com.twitter.product_mixer.core.model.marshalling.response.urt.item.tweet.TweetItem
import com.twitter.product_mixer.core.pipeline.PipelineQuery
/**
* Builds serialized tweet type metrics controller data and updates Client Event Details
* and Candidate Presentations with this info.
*
* Currently only updates presentation of Item Candidates. This needs to be updated
* when modules are added.
*
* This is implemented as a Selector instead of a Decorator in the Candidate Pipeline
* because we need to add controller data that looks at the final timeline as a whole
* (e.g. served size, final candidate positions).
*
* @param candidatePipelines - only candidates from the specified pipeline will be updated
*/
case class UpdateHomeClientEventDetails(candidatePipelines: Set[CandidatePipelineIdentifier])
extends Selector[PipelineQuery] {
override val pipelineScope: CandidateScope = SpecificPipelines(candidatePipelines)
private val detailsBuilder = HomeClientEventDetailsBuilder()
override def apply(
query: PipelineQuery,
remainingCandidates: Seq[CandidateWithDetails],
result: Seq[CandidateWithDetails]
): SelectorResult = {
val selectedCandidates = result.filter(pipelineScope.contains)
val randomTweetsByPosition = result
.map(_.features.getOrElse(IsRandomTweetFeature, false))
.zipWithIndex.map(_.swap).toMap
val resultFeatures = FeatureMapBuilder()
.add(ServedSizeFeature, Some(selectedCandidates.size))
.add(HasRandomTweetFeature, randomTweetsByPosition.valuesIterator.contains(true))
.build()
val updatedResult = result.zipWithIndex.map {
case (item @ ItemCandidateWithDetails(candidate, _, _), position)
if pipelineScope.contains(item) =>
val resultCandidateFeatures = FeatureMapBuilder()
.add(PositionFeature, Some(position))
.add(IsRandomTweetAboveFeature, randomTweetsByPosition.getOrElse(position - 1, false))
.build()
updateItemPresentation(query, item, resultFeatures, resultCandidateFeatures)
case (module @ ModuleCandidateWithDetails(candidates, presentation, features), position)
if pipelineScope.contains(module) =>
val resultCandidateFeatures = FeatureMapBuilder()
.add(PositionFeature, Some(position))
.add(IsRandomTweetAboveFeature, randomTweetsByPosition.getOrElse(position - 1, false))
.add(ServedInConversationModuleFeature, true)
.add(ConversationModule2DisplayedTweetsFeature, module.candidates.size == 2)
.add(
ConversationModuleHasGapFeature,
module.candidates.last.features.getOrElse(AncestorsFeature, Seq.empty).size > 2)
.build()
val updatedItemCandidates =
candidates.map(updateItemPresentation(query, _, resultFeatures, resultCandidateFeatures))
val updatedCandidateFeatures = features ++ resultFeatures ++ resultCandidateFeatures
val updatedPresentation = presentation.map {
case urtModule @ UrtModulePresentation(timelineModule) =>
val clientEventDetails =
detailsBuilder(
query,
candidates.last.candidate,
query.features.get ++ updatedCandidateFeatures)
val updatedClientEventInfo =
timelineModule.clientEventInfo.map(_.copy(details = clientEventDetails))
val updatedTimelineModule =
timelineModule.copy(clientEventInfo = updatedClientEventInfo)
urtModule.copy(timelineModule = updatedTimelineModule)
}
module.copy(
candidates = updatedItemCandidates,
presentation = updatedPresentation,
features = updatedCandidateFeatures
)
case (any, position) => any
}
SelectorResult(remainingCandidates = remainingCandidates, result = updatedResult)
}
private def updateItemPresentation(
query: PipelineQuery,
item: ItemCandidateWithDetails,
resultCandidateFeatures: FeatureMap,
resultFeatures: FeatureMap,
): ItemCandidateWithDetails = {
val updatedItemCandidateFeatures = item.features ++ resultFeatures ++ resultCandidateFeatures
val updatedPresentation = item.presentation.map {
case urtItem @ UrtItemPresentation(timelineItem: TweetItem, _) =>
val clientEventDetails =
detailsBuilder(query, item.candidate, query.features.get ++ updatedItemCandidateFeatures)
val updatedClientEventInfo =
timelineItem.clientEventInfo.map(_.copy(details = clientEventDetails))
val updatedTimelineItem = timelineItem.copy(clientEventInfo = updatedClientEventInfo)
urtItem.copy(timelineItem = updatedTimelineItem)
case any => any
}
item.copy(presentation = updatedPresentation, features = updatedItemCandidateFeatures)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/selector/UpdateNewTweetsPillDecoration.scala | package com.twitter.home_mixer.functional_component.selector
import com.twitter.home_mixer.functional_component.selector.UpdateNewTweetsPillDecoration.NumAvatars
import com.twitter.home_mixer.model.HomeFeatures.AuthorIdFeature
import com.twitter.home_mixer.model.HomeFeatures.IsRetweetFeature
import com.twitter.home_mixer.model.request.HasDeviceContext
import com.twitter.home_mixer.param.HomeGlobalParams.EnableNewTweetsPillAvatarsParam
import com.twitter.home_mixer.util.CandidatesUtil
import com.twitter.product_mixer.component_library.model.candidate.ShowAlertCandidate
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.component_library.model.presentation.urt.UrtItemPresentation
import com.twitter.product_mixer.core.functional_component.common.CandidateScope
import com.twitter.product_mixer.core.functional_component.selector.Selector
import com.twitter.product_mixer.core.functional_component.selector.SelectorResult
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.model.common.presentation.ItemCandidateWithDetails
import com.twitter.product_mixer.core.model.marshalling.response.urt.ShowAlert
import com.twitter.product_mixer.core.model.marshalling.response.urt.richtext.RichText
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stringcenter.client.StringCenter
import com.twitter.stringcenter.client.core.ExternalString
object UpdateNewTweetsPillDecoration {
val NumAvatars = 3
}
case class UpdateNewTweetsPillDecoration[Query <: PipelineQuery with HasDeviceContext](
override val pipelineScope: CandidateScope,
stringCenter: StringCenter,
seeNewTweetsString: ExternalString,
tweetedString: ExternalString)
extends Selector[Query] {
override def apply(
query: Query,
remainingCandidates: Seq[CandidateWithDetails],
result: Seq[CandidateWithDetails]
): SelectorResult = {
val (alerts, otherCandidates) =
remainingCandidates.partition(candidate =>
candidate.isCandidateType[ShowAlertCandidate]() && pipelineScope.contains(candidate))
val updatedCandidates = alerts
.collectFirst {
case newTweetsPill: ItemCandidateWithDetails =>
val userIds = CandidatesUtil
.getItemCandidatesWithOnlyModuleLast(result)
.filter(candidate =>
candidate.isCandidateType[TweetCandidate]() && pipelineScope.contains(candidate))
.filterNot(_.features.getOrElse(IsRetweetFeature, false))
.flatMap(_.features.getOrElse(AuthorIdFeature, None))
.filterNot(_ == query.getRequiredUserId)
.distinct
val updatedPresentation = newTweetsPill.presentation.map {
case presentation: UrtItemPresentation =>
presentation.timelineItem match {
case alert: ShowAlert =>
val text = if (useAvatars(query, userIds)) tweetedString else seeNewTweetsString
val richText = RichText(
text = stringCenter.prepare(text),
entities = List.empty,
rtl = None,
alignment = None)
val updatedAlert =
alert.copy(userIds = Some(userIds.take(NumAvatars)), richText = Some(richText))
presentation.copy(timelineItem = updatedAlert)
}
}
otherCandidates :+ newTweetsPill.copy(presentation = updatedPresentation)
}.getOrElse(remainingCandidates)
SelectorResult(remainingCandidates = updatedCandidates, result = result)
}
private def useAvatars(query: Query, userIds: Seq[Long]): Boolean = {
val enableAvatars = query.params(EnableNewTweetsPillAvatarsParam)
enableAvatars && userIds.size >= NumAvatars
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/side_effect/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"3rdparty/jvm/javax/inject:javax.inject",
"eventbus/client/src/main/scala/com/twitter/eventbus/client",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/decorator",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/decorator/builder",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timeline_logging",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timelines",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/param",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/service",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/util",
"kafka/finagle-kafka/finatra-kafka/src/main/scala",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/decorator/urt",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/model/candidate",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/model/presentation/urt",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/pipeline/candidate/who_to_follow_module",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/pipeline/candidate/who_to_subscribe_module",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/side_effect",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/product",
"src/scala/com/twitter/timelines/prediction/common/adapters",
"src/scala/com/twitter/timelines/prediction/features/common",
"src/thrift/com/twitter/timelines/impression:thrift-scala",
"src/thrift/com/twitter/timelines/impression_bloom_filter:thrift-scala",
"src/thrift/com/twitter/timelines/impression_store:thrift-scala",
"src/thrift/com/twitter/timelines/served_candidates_logging:served_candidates_logging-scala",
"src/thrift/com/twitter/timelines/suggests/common:poly_data_record-java",
"src/thrift/com/twitter/timelines/timeline_logging:thrift-scala",
"src/thrift/com/twitter/user_session_store:thrift-scala",
"timelinemixer/server/src/main/scala/com/twitter/timelinemixer/injection/store/persistence",
"timelines/ml:kafka",
"timelines/ml/cont_train/common/client/src/main/scala/com/twitter/timelines/ml/cont_train/common/client/kafka",
"timelines/ml/cont_train/common/domain/src/main/scala/com/twitter/timelines/ml/cont_train/common/domain/non_scalding",
"timelines/src/main/scala/com/twitter/timelines/clientconfig",
"timelines/src/main/scala/com/twitter/timelines/clients/manhattan/store",
"timelines/src/main/scala/com/twitter/timelines/impressionstore/impressionbloomfilter",
"timelines/src/main/scala/com/twitter/timelines/impressionstore/store",
"timelines/src/main/scala/com/twitter/timelines/injection/scribe",
"timelineservice/common:model",
"user_session_store/src/main/scala/com/twitter/user_session_store",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/side_effect/ClientEventsBuilder.scala | package com.twitter.home_mixer.functional_component.side_effect
import com.twitter.conversions.DurationOps._
import com.twitter.home_mixer.functional_component.decorator.HomeQueryTypePredicates
import com.twitter.home_mixer.functional_component.decorator.builder.HomeTweetTypePredicates
import com.twitter.home_mixer.model.HomeFeatures.AccountAgeFeature
import com.twitter.home_mixer.model.HomeFeatures.SuggestTypeFeature
import com.twitter.home_mixer.model.HomeFeatures.VideoDurationMsFeature
import com.twitter.home_mixer.model.request.FollowingProduct
import com.twitter.home_mixer.model.request.ForYouProduct
import com.twitter.home_mixer.model.request.ListTweetsProduct
import com.twitter.home_mixer.model.request.SubscribedProduct
import com.twitter.product_mixer.component_library.side_effect.ScribeClientEventSideEffect.ClientEvent
import com.twitter.product_mixer.component_library.side_effect.ScribeClientEventSideEffect.EventNamespace
import com.twitter.product_mixer.core.feature.featuremap.FeatureMap
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.model.common.presentation.ItemCandidateWithDetails
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.timelines.injection.scribe.InjectionScribeUtil
private[side_effect] sealed trait ClientEventsBuilder {
private val FollowingSection = Some("latest")
private val ForYouSection = Some("home")
private val ListTweetsSection = Some("list")
private val SubscribedSection = Some("subscribed")
protected def section(query: PipelineQuery): Option[String] = {
query.product match {
case FollowingProduct => FollowingSection
case ForYouProduct => ForYouSection
case ListTweetsProduct => ListTweetsSection
case SubscribedProduct => SubscribedSection
case other => throw new UnsupportedOperationException(s"Unknown product: $other")
}
}
protected def count(
candidates: Seq[CandidateWithDetails],
predicate: FeatureMap => Boolean = _ => true,
queryFeatures: FeatureMap = FeatureMap.empty
): Option[Long] = Some(candidates.view.count(item => predicate(item.features ++ queryFeatures)))
protected def sum(
candidates: Seq[CandidateWithDetails],
predicate: FeatureMap => Option[Int],
queryFeatures: FeatureMap = FeatureMap.empty
): Option[Long] =
Some(candidates.view.flatMap(item => predicate(item.features ++ queryFeatures)).sum)
}
private[side_effect] object ServedEventsBuilder extends ClientEventsBuilder {
private val ServedTweetsAction = Some("served_tweets")
private val ServedUsersAction = Some("served_users")
private val InjectedComponent = Some("injected")
private val PromotedComponent = Some("promoted")
private val WhoToFollowComponent = Some("who_to_follow")
private val WhoToSubscribeComponent = Some("who_to_subscribe")
private val WithVideoDurationComponent = Some("with_video_duration")
private val VideoDurationSumElement = Some("video_duration_sum")
private val NumVideosElement = Some("num_videos")
def build(
query: PipelineQuery,
injectedTweets: Seq[ItemCandidateWithDetails],
promotedTweets: Seq[ItemCandidateWithDetails],
whoToFollowUsers: Seq[ItemCandidateWithDetails],
whoToSubscribeUsers: Seq[ItemCandidateWithDetails]
): Seq[ClientEvent] = {
val baseEventNamespace = EventNamespace(
section = section(query),
action = ServedTweetsAction
)
val overallServedEvents = Seq(
ClientEvent(baseEventNamespace, eventValue = count(injectedTweets ++ promotedTweets)),
ClientEvent(
baseEventNamespace.copy(component = InjectedComponent),
eventValue = count(injectedTweets)),
ClientEvent(
baseEventNamespace.copy(component = PromotedComponent),
eventValue = count(promotedTweets)),
ClientEvent(
baseEventNamespace.copy(component = WhoToFollowComponent, action = ServedUsersAction),
eventValue = count(whoToFollowUsers)),
ClientEvent(
baseEventNamespace.copy(component = WhoToSubscribeComponent, action = ServedUsersAction),
eventValue = count(whoToSubscribeUsers)),
)
val tweetTypeServedEvents = HomeTweetTypePredicates.PredicateMap.map {
case (tweetType, predicate) =>
ClientEvent(
baseEventNamespace.copy(component = InjectedComponent, element = Some(tweetType)),
eventValue = count(injectedTweets, predicate, query.features.getOrElse(FeatureMap.empty))
)
}.toSeq
val suggestTypeServedEvents = injectedTweets
.flatMap(_.features.getOrElse(SuggestTypeFeature, None))
.map {
InjectionScribeUtil.scribeComponent
}
.groupBy(identity).map {
case (suggestType, group) =>
ClientEvent(
baseEventNamespace.copy(component = suggestType),
eventValue = Some(group.size.toLong))
}.toSeq
// Video duration events
val numVideosEvent = ClientEvent(
baseEventNamespace.copy(component = WithVideoDurationComponent, element = NumVideosElement),
eventValue = count(injectedTweets, _.getOrElse(VideoDurationMsFeature, None).nonEmpty)
)
val videoDurationSumEvent = ClientEvent(
baseEventNamespace
.copy(component = WithVideoDurationComponent, element = VideoDurationSumElement),
eventValue = sum(injectedTweets, _.getOrElse(VideoDurationMsFeature, None))
)
val videoEvents = Seq(numVideosEvent, videoDurationSumEvent)
overallServedEvents ++ tweetTypeServedEvents ++ suggestTypeServedEvents ++ videoEvents
}
}
private[side_effect] object EmptyTimelineEventsBuilder extends ClientEventsBuilder {
private val EmptyAction = Some("empty")
private val AccountAgeLessThan30MinutesComponent = Some("account_age_less_than_30_minutes")
private val ServedNonPromotedTweetElement = Some("served_non_promoted_tweet")
def build(
query: PipelineQuery,
injectedTweets: Seq[ItemCandidateWithDetails]
): Seq[ClientEvent] = {
val baseEventNamespace = EventNamespace(
section = section(query),
action = EmptyAction
)
// Empty timeline events
val accountAgeLessThan30Minutes = query.features
.flatMap(_.getOrElse(AccountAgeFeature, None))
.exists(_.untilNow < 30.minutes)
val isEmptyTimeline = count(injectedTweets).contains(0L)
val predicates = Seq(
None -> isEmptyTimeline,
AccountAgeLessThan30MinutesComponent -> (isEmptyTimeline && accountAgeLessThan30Minutes)
)
for {
(component, predicate) <- predicates
if predicate
} yield ClientEvent(
baseEventNamespace.copy(component = component, element = ServedNonPromotedTweetElement))
}
}
private[side_effect] object QueryEventsBuilder extends ClientEventsBuilder {
private val ServedSizePredicateMap: Map[String, Int => Boolean] = Map(
("size_is_empty", _ <= 0),
("size_at_most_5", _ <= 5),
("size_at_most_10", _ <= 10),
("size_at_most_35", _ <= 35)
)
def build(
query: PipelineQuery,
injectedTweets: Seq[ItemCandidateWithDetails]
): Seq[ClientEvent] = {
val baseEventNamespace = EventNamespace(
section = section(query)
)
val queryFeatureMap = query.features.getOrElse(FeatureMap.empty)
val servedSizeQueryEvents =
for {
(queryPredicateName, queryPredicate) <- HomeQueryTypePredicates.PredicateMap
if queryPredicate(queryFeatureMap)
(servedSizePredicateName, servedSizePredicate) <- ServedSizePredicateMap
if servedSizePredicate(injectedTweets.size)
} yield ClientEvent(
baseEventNamespace
.copy(component = Some(servedSizePredicateName), action = Some(queryPredicateName)))
servedSizeQueryEvents.toSeq
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/side_effect/HomeScribeClientEventSideEffect.scala | package com.twitter.home_mixer.functional_component.side_effect
import com.twitter.clientapp.thriftscala.LogEvent
import com.twitter.home_mixer.service.HomeMixerAlertConfig
import com.twitter.home_mixer.util.CandidatesUtil
import com.twitter.logpipeline.client.common.EventPublisher
import com.twitter.product_mixer.component_library.side_effect.ScribeClientEventSideEffect
import com.twitter.product_mixer.core.functional_component.side_effect.PipelineResultSideEffect
import com.twitter.product_mixer.core.model.common.identifier.CandidatePipelineIdentifier
import com.twitter.product_mixer.core.model.common.identifier.SideEffectIdentifier
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.model.marshalling.response.urt.Timeline
import com.twitter.product_mixer.core.pipeline.PipelineQuery
/**
* Side effect that logs served tweet metrics to Scribe as client events.
*/
case class HomeScribeClientEventSideEffect(
enableScribeClientEvents: Boolean,
override val logPipelinePublisher: EventPublisher[LogEvent],
injectedTweetsCandidatePipelineIdentifiers: Seq[CandidatePipelineIdentifier],
adsCandidatePipelineIdentifier: Option[CandidatePipelineIdentifier] = None,
whoToFollowCandidatePipelineIdentifier: Option[CandidatePipelineIdentifier] = None,
whoToSubscribeCandidatePipelineIdentifier: Option[CandidatePipelineIdentifier] = None)
extends ScribeClientEventSideEffect[PipelineQuery, Timeline]
with PipelineResultSideEffect.Conditionally[
PipelineQuery,
Timeline
] {
override val identifier: SideEffectIdentifier = SideEffectIdentifier("HomeScribeClientEvent")
override val page = "timelinemixer"
override def onlyIf(
query: PipelineQuery,
selectedCandidates: Seq[CandidateWithDetails],
remainingCandidates: Seq[CandidateWithDetails],
droppedCandidates: Seq[CandidateWithDetails],
response: Timeline
): Boolean = enableScribeClientEvents
override def buildClientEvents(
query: PipelineQuery,
selectedCandidates: Seq[CandidateWithDetails],
remainingCandidates: Seq[CandidateWithDetails],
droppedCandidates: Seq[CandidateWithDetails],
response: Timeline
): Seq[ScribeClientEventSideEffect.ClientEvent] = {
val itemCandidates = CandidatesUtil.getItemCandidates(selectedCandidates)
val sources = itemCandidates.groupBy(_.source)
val injectedTweets =
injectedTweetsCandidatePipelineIdentifiers.flatMap(sources.getOrElse(_, Seq.empty))
val promotedTweets = adsCandidatePipelineIdentifier.flatMap(sources.get).toSeq.flatten
// WhoToFollow and WhoToSubscribe modules are not required for all home-mixer products, e.g. list tweets timeline.
val whoToFollowUsers = whoToFollowCandidatePipelineIdentifier.flatMap(sources.get).toSeq.flatten
val whoToSubscribeUsers =
whoToSubscribeCandidatePipelineIdentifier.flatMap(sources.get).toSeq.flatten
val servedEvents = ServedEventsBuilder
.build(query, injectedTweets, promotedTweets, whoToFollowUsers, whoToSubscribeUsers)
val emptyTimelineEvents = EmptyTimelineEventsBuilder.build(query, injectedTweets)
val queryEvents = QueryEventsBuilder.build(query, injectedTweets)
(servedEvents ++ emptyTimelineEvents ++ queryEvents).filter(_.eventValue.forall(_ > 0))
}
override val alerts = Seq(
HomeMixerAlertConfig.BusinessHours.defaultSuccessRateAlert(99.9)
)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/side_effect/HomeScribeServedCandidatesSideEffect.scala | package com.twitter.home_mixer.functional_component.side_effect
import com.twitter.finagle.tracing.Trace
import com.twitter.home_mixer.marshaller.timeline_logging.PromotedTweetDetailsMarshaller
import com.twitter.home_mixer.marshaller.timeline_logging.TweetDetailsMarshaller
import com.twitter.home_mixer.marshaller.timeline_logging.WhoToFollowDetailsMarshaller
import com.twitter.home_mixer.model.HomeFeatures.GetInitialFeature
import com.twitter.home_mixer.model.HomeFeatures.GetMiddleFeature
import com.twitter.home_mixer.model.HomeFeatures.GetNewerFeature
import com.twitter.home_mixer.model.HomeFeatures.GetOlderFeature
import com.twitter.home_mixer.model.HomeFeatures.HasDarkRequestFeature
import com.twitter.home_mixer.model.HomeFeatures.RequestJoinIdFeature
import com.twitter.home_mixer.model.HomeFeatures.ScoreFeature
import com.twitter.home_mixer.model.HomeFeatures.ServedRequestIdFeature
import com.twitter.home_mixer.model.request.DeviceContext.RequestContext
import com.twitter.home_mixer.model.request.HasDeviceContext
import com.twitter.home_mixer.model.request.HasSeenTweetIds
import com.twitter.home_mixer.model.request.FollowingProduct
import com.twitter.home_mixer.model.request.ForYouProduct
import com.twitter.home_mixer.model.request.SubscribedProduct
import com.twitter.home_mixer.param.HomeMixerFlagName.ScribeServedCandidatesFlag
import com.twitter.home_mixer.param.HomeGlobalParams.EnableScribeServedCandidatesParam
import com.twitter.home_mixer.service.HomeMixerAlertConfig
import com.twitter.inject.annotations.Flag
import com.twitter.logpipeline.client.common.EventPublisher
import com.twitter.product_mixer.component_library.model.candidate.BaseTweetCandidate
import com.twitter.product_mixer.component_library.model.candidate.BaseUserCandidate
import com.twitter.product_mixer.component_library.pipeline.candidate.who_to_follow_module.WhoToFollowCandidateDecorator
import com.twitter.product_mixer.component_library.pipeline.candidate.who_to_subscribe_module.WhoToSubscribeCandidateDecorator
import com.twitter.product_mixer.component_library.side_effect.ScribeLogEventSideEffect
import com.twitter.product_mixer.core.functional_component.side_effect.PipelineResultSideEffect
import com.twitter.product_mixer.core.model.common.identifier.SideEffectIdentifier
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.model.common.presentation.ItemCandidateWithDetails
import com.twitter.product_mixer.core.model.common.presentation.ModuleCandidateWithDetails
import com.twitter.product_mixer.core.model.marshalling.response.urt.AddEntriesTimelineInstruction
import com.twitter.product_mixer.core.model.marshalling.response.urt.ModuleItem
import com.twitter.product_mixer.core.model.marshalling.response.urt.Timeline
import com.twitter.product_mixer.core.model.marshalling.response.urt.TimelineModule
import com.twitter.product_mixer.core.model.marshalling.response.urt.item.tweet.TweetItem
import com.twitter.product_mixer.core.model.marshalling.response.urt.item.user.UserItem
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.timelines.timeline_logging.{thriftscala => thrift}
import com.twitter.util.Time
import javax.inject.Inject
import javax.inject.Singleton
/**
* Side effect that logs home timeline served candidates to Scribe.
*/
@Singleton
class HomeScribeServedCandidatesSideEffect @Inject() (
@Flag(ScribeServedCandidatesFlag) enableScribeServedCandidates: Boolean,
scribeEventPublisher: EventPublisher[thrift.ServedEntry])
extends ScribeLogEventSideEffect[
thrift.ServedEntry,
PipelineQuery with HasSeenTweetIds with HasDeviceContext,
Timeline
]
with PipelineResultSideEffect.Conditionally[
PipelineQuery with HasSeenTweetIds with HasDeviceContext,
Timeline
] {
override val identifier: SideEffectIdentifier = SideEffectIdentifier("HomeScribeServedCandidates")
override def onlyIf(
query: PipelineQuery with HasSeenTweetIds with HasDeviceContext,
selectedCandidates: Seq[CandidateWithDetails],
remainingCandidates: Seq[CandidateWithDetails],
droppedCandidates: Seq[CandidateWithDetails],
response: Timeline
): Boolean = enableScribeServedCandidates && query.params(EnableScribeServedCandidatesParam)
override def buildLogEvents(
query: PipelineQuery with HasSeenTweetIds with HasDeviceContext,
selectedCandidates: Seq[CandidateWithDetails],
remainingCandidates: Seq[CandidateWithDetails],
droppedCandidates: Seq[CandidateWithDetails],
response: Timeline
): Seq[thrift.ServedEntry] = {
val timelineType = query.product match {
case FollowingProduct => thrift.TimelineType.HomeLatest
case ForYouProduct => thrift.TimelineType.Home
case SubscribedProduct => thrift.TimelineType.HomeSubscribed
case other => throw new UnsupportedOperationException(s"Unknown product: $other")
}
val requestProvenance = query.deviceContext.map { deviceContext =>
deviceContext.requestContextValue match {
case RequestContext.Foreground => thrift.RequestProvenance.Foreground
case RequestContext.Launch => thrift.RequestProvenance.Launch
case RequestContext.PullToRefresh => thrift.RequestProvenance.Ptr
case _ => thrift.RequestProvenance.Other
}
}
val queryType = query.features.map { featureMap =>
if (featureMap.getOrElse(GetOlderFeature, false)) thrift.QueryType.GetOlder
else if (featureMap.getOrElse(GetNewerFeature, false)) thrift.QueryType.GetNewer
else if (featureMap.getOrElse(GetMiddleFeature, false)) thrift.QueryType.GetMiddle
else if (featureMap.getOrElse(GetInitialFeature, false)) thrift.QueryType.GetInitial
else thrift.QueryType.Other
}
val requestInfo = thrift.RequestInfo(
requestTimeMs = query.queryTime.inMilliseconds,
traceId = Trace.id.traceId.toLong,
userId = query.getOptionalUserId,
clientAppId = query.clientContext.appId,
hasDarkRequest = query.features.flatMap(_.getOrElse(HasDarkRequestFeature, None)),
parentId = Some(Trace.id.parentId.toLong),
spanId = Some(Trace.id.spanId.toLong),
timelineType = Some(timelineType),
ipAddress = query.clientContext.ipAddress,
userAgent = query.clientContext.userAgent,
queryType = queryType,
requestProvenance = requestProvenance,
languageCode = query.clientContext.languageCode,
countryCode = query.clientContext.countryCode,
requestEndTimeMs = Some(Time.now.inMilliseconds),
servedRequestId = query.features.flatMap(_.getOrElse(ServedRequestIdFeature, None)),
requestJoinId = query.features.flatMap(_.getOrElse(RequestJoinIdFeature, None))
)
val tweetIdToItemCandidateMap: Map[Long, ItemCandidateWithDetails] =
selectedCandidates.flatMap {
case item: ItemCandidateWithDetails if item.candidate.isInstanceOf[BaseTweetCandidate] =>
Seq((item.candidateIdLong, item))
case module: ModuleCandidateWithDetails
if module.candidates.headOption.exists(_.candidate.isInstanceOf[BaseTweetCandidate]) =>
module.candidates.map(item => (item.candidateIdLong, item))
case _ => Seq.empty
}.toMap
val userIdToItemCandidateMap: Map[Long, ItemCandidateWithDetails] =
selectedCandidates.flatMap {
case module: ModuleCandidateWithDetails
if module.candidates.forall(_.candidate.isInstanceOf[BaseUserCandidate]) =>
module.candidates.map { item =>
(item.candidateIdLong, item)
}
case _ => Seq.empty
}.toMap
response.instructions.zipWithIndex
.collect {
case (AddEntriesTimelineInstruction(entries), index) =>
entries.collect {
case entry: TweetItem if entry.promotedMetadata.isDefined =>
val promotedTweetDetails = PromotedTweetDetailsMarshaller(entry, index)
Seq(
thrift.EntryInfo(
id = entry.id,
position = index.shortValue(),
entryId = entry.entryIdentifier,
entryType = thrift.EntryType.PromotedTweet,
sortIndex = entry.sortIndex,
verticalSize = Some(1),
displayType = Some(entry.displayType.toString),
details = Some(thrift.ItemDetails.PromotedTweetDetails(promotedTweetDetails))
)
)
case entry: TweetItem =>
val candidate = tweetIdToItemCandidateMap(entry.id)
val tweetDetails = TweetDetailsMarshaller(entry, candidate)
Seq(
thrift.EntryInfo(
id = candidate.candidateIdLong,
position = index.shortValue(),
entryId = entry.entryIdentifier,
entryType = thrift.EntryType.Tweet,
sortIndex = entry.sortIndex,
verticalSize = Some(1),
score = candidate.features.getOrElse(ScoreFeature, None),
displayType = Some(entry.displayType.toString),
details = Some(thrift.ItemDetails.TweetDetails(tweetDetails))
)
)
case module: TimelineModule
if module.entryNamespace.toString == WhoToFollowCandidateDecorator.EntryNamespaceString =>
module.items.collect {
case ModuleItem(entry: UserItem, _, _) =>
val candidate = userIdToItemCandidateMap(entry.id)
val whoToFollowDetails = WhoToFollowDetailsMarshaller(entry, candidate)
thrift.EntryInfo(
id = entry.id,
position = index.shortValue(),
entryId = module.entryIdentifier,
entryType = thrift.EntryType.WhoToFollowModule,
sortIndex = module.sortIndex,
score = candidate.features.getOrElse(ScoreFeature, None),
displayType = Some(entry.displayType.toString),
details = Some(thrift.ItemDetails.WhoToFollowDetails(whoToFollowDetails))
)
}
case module: TimelineModule
if module.entryNamespace.toString == WhoToSubscribeCandidateDecorator.EntryNamespaceString =>
module.items.collect {
case ModuleItem(entry: UserItem, _, _) =>
val candidate = userIdToItemCandidateMap(entry.id)
val whoToSubscribeDetails = WhoToFollowDetailsMarshaller(entry, candidate)
thrift.EntryInfo(
id = entry.id,
position = index.shortValue(),
entryId = module.entryIdentifier,
entryType = thrift.EntryType.WhoToSubscribeModule,
sortIndex = module.sortIndex,
score = candidate.features.getOrElse(ScoreFeature, None),
displayType = Some(entry.displayType.toString),
details = Some(thrift.ItemDetails.WhoToFollowDetails(whoToSubscribeDetails))
)
}
case module: TimelineModule
if module.sortIndex.isDefined && module.items.headOption.exists(
_.item.isInstanceOf[TweetItem]) =>
module.items.collect {
case ModuleItem(entry: TweetItem, _, _) =>
val candidate = tweetIdToItemCandidateMap(entry.id)
thrift.EntryInfo(
id = entry.id,
position = index.shortValue(),
entryId = module.entryIdentifier,
entryType = thrift.EntryType.ConversationModule,
sortIndex = module.sortIndex,
score = candidate.features.getOrElse(ScoreFeature, None),
displayType = Some(entry.displayType.toString)
)
}
case _ => Seq.empty
}.flatten
// Other instructions
case _ => Seq.empty[thrift.EntryInfo]
}.flatten.map { entryInfo =>
thrift.ServedEntry(
entry = Some(entryInfo),
request = requestInfo
)
}
}
override val logPipelinePublisher: EventPublisher[thrift.ServedEntry] =
scribeEventPublisher
override val alerts = Seq(
HomeMixerAlertConfig.BusinessHours.defaultSuccessRateAlert()
)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/side_effect/PublishClientSentImpressionsEventBusSideEffect.scala | package com.twitter.home_mixer.functional_component.side_effect
import com.twitter.eventbus.client.EventBusPublisher
import com.twitter.home_mixer.model.request.FollowingProduct
import com.twitter.home_mixer.model.request.ForYouProduct
import com.twitter.home_mixer.model.request.SubscribedProduct
import com.twitter.home_mixer.model.request.HasSeenTweetIds
import com.twitter.home_mixer.service.HomeMixerAlertConfig
import com.twitter.product_mixer.core.functional_component.side_effect.PipelineResultSideEffect
import com.twitter.product_mixer.core.model.common.identifier.SideEffectIdentifier
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.model.marshalling.HasMarshalling
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
import com.twitter.timelines.impressionstore.thriftscala.Impression
import com.twitter.timelines.impressionstore.thriftscala.ImpressionList
import com.twitter.timelines.impressionstore.thriftscala.PublishedImpressionList
import com.twitter.timelines.impressionstore.thriftscala.SurfaceArea
import com.twitter.util.Time
import javax.inject.Inject
import javax.inject.Singleton
object PublishClientSentImpressionsEventBusSideEffect {
val HomeSurfaceArea: Option[Set[SurfaceArea]] = Some(Set(SurfaceArea.HomeTimeline))
val HomeLatestSurfaceArea: Option[Set[SurfaceArea]] = Some(Set(SurfaceArea.HomeLatestTimeline))
val HomeSubscribedSurfaceArea: Option[Set[SurfaceArea]] = Some(Set(SurfaceArea.HomeSubscribed))
}
/**
* Side effect that publishes seen tweet IDs sent from clients. The seen tweet IDs are sent to a
* heron topology which writes to a memcache dataset.
*/
@Singleton
class PublishClientSentImpressionsEventBusSideEffect @Inject() (
eventBusPublisher: EventBusPublisher[PublishedImpressionList])
extends PipelineResultSideEffect[PipelineQuery with HasSeenTweetIds, HasMarshalling]
with PipelineResultSideEffect.Conditionally[
PipelineQuery with HasSeenTweetIds,
HasMarshalling
] {
import PublishClientSentImpressionsEventBusSideEffect._
override val identifier: SideEffectIdentifier =
SideEffectIdentifier("PublishClientSentImpressionsEventBus")
override def onlyIf(
query: PipelineQuery with HasSeenTweetIds,
selectedCandidates: Seq[CandidateWithDetails],
remainingCandidates: Seq[CandidateWithDetails],
droppedCandidates: Seq[CandidateWithDetails],
response: HasMarshalling
): Boolean = query.seenTweetIds.exists(_.nonEmpty)
def buildEvents(
query: PipelineQuery with HasSeenTweetIds,
currentTime: Long
): Option[Seq[Impression]] = {
val surfaceArea = query.product match {
case ForYouProduct => HomeSurfaceArea
case FollowingProduct => HomeLatestSurfaceArea
case SubscribedProduct => HomeSubscribedSurfaceArea
case _ => None
}
query.seenTweetIds.map { seenTweetIds =>
seenTweetIds.map { tweetId =>
Impression(
tweetId = tweetId,
impressionTime = Some(currentTime),
surfaceAreas = surfaceArea
)
}
}
}
final override def apply(
inputs: PipelineResultSideEffect.Inputs[PipelineQuery with HasSeenTweetIds, HasMarshalling]
): Stitch[Unit] = {
val currentTime = Time.now.inMilliseconds
val impressions = buildEvents(inputs.query, currentTime)
Stitch.callFuture(
eventBusPublisher.publish(
PublishedImpressionList(
inputs.query.getRequiredUserId,
ImpressionList(impressions),
currentTime
)
)
)
}
override val alerts = Seq(
HomeMixerAlertConfig.BusinessHours.defaultSuccessRateAlert(99.4)
)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/side_effect/PublishClientSentImpressionsManhattanSideEffect.scala | package com.twitter.home_mixer.functional_component.side_effect
import com.twitter.home_mixer.model.HomeFeatures.TweetImpressionsFeature
import com.twitter.home_mixer.model.request.HasSeenTweetIds
import com.twitter.home_mixer.service.HomeMixerAlertConfig
import com.twitter.product_mixer.core.functional_component.side_effect.PipelineResultSideEffect
import com.twitter.product_mixer.core.model.common.identifier.SideEffectIdentifier
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.model.marshalling.HasMarshalling
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
import com.twitter.timelines.impression.{thriftscala => t}
import com.twitter.timelines.impressionstore.store.ManhattanTweetImpressionStoreClient
import javax.inject.Inject
import javax.inject.Singleton
/**
* Side effect that updates the timelines tweet impression
* store (Manhattan) with seen tweet IDs sent from clients
*/
@Singleton
class PublishClientSentImpressionsManhattanSideEffect @Inject() (
manhattanTweetImpressionStoreClient: ManhattanTweetImpressionStoreClient)
extends PipelineResultSideEffect[PipelineQuery with HasSeenTweetIds, HasMarshalling]
with PipelineResultSideEffect.Conditionally[
PipelineQuery with HasSeenTweetIds,
HasMarshalling
] {
override val identifier: SideEffectIdentifier =
SideEffectIdentifier("PublishClientSentImpressionsManhattan")
override def onlyIf(
query: PipelineQuery with HasSeenTweetIds,
selectedCandidates: Seq[CandidateWithDetails],
remainingCandidates: Seq[CandidateWithDetails],
droppedCandidates: Seq[CandidateWithDetails],
response: HasMarshalling
): Boolean = query.seenTweetIds.exists(_.nonEmpty)
def buildEvents(query: PipelineQuery): Option[(Long, t.TweetImpressionsEntries)] = {
query.features.flatMap { featureMap =>
val impressions = featureMap.getOrElse(TweetImpressionsFeature, Seq.empty)
if (impressions.nonEmpty)
Some((query.getRequiredUserId, t.TweetImpressionsEntries(impressions)))
else None
}
}
final override def apply(
inputs: PipelineResultSideEffect.Inputs[PipelineQuery with HasSeenTweetIds, HasMarshalling]
): Stitch[Unit] = {
val events = buildEvents(inputs.query)
Stitch
.traverse(events) {
case (key, value) => manhattanTweetImpressionStoreClient.write(key, value)
}
.unit
}
override val alerts = Seq(
HomeMixerAlertConfig.BusinessHours.defaultSuccessRateAlert(99.4)
)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/side_effect/PublishImpressionBloomFilterSideEffect.scala | package com.twitter.home_mixer.functional_component.side_effect
import com.twitter.home_mixer.model.HomeFeatures.ImpressionBloomFilterFeature
import com.twitter.home_mixer.model.request.HasSeenTweetIds
import com.twitter.home_mixer.param.HomeGlobalParams.EnableImpressionBloomFilter
import com.twitter.home_mixer.service.HomeMixerAlertConfig
import com.twitter.product_mixer.core.functional_component.side_effect.PipelineResultSideEffect
import com.twitter.product_mixer.core.model.common.identifier.SideEffectIdentifier
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.model.marshalling.HasMarshalling
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
import com.twitter.timelines.clients.manhattan.store.ManhattanStoreClient
import com.twitter.timelines.impressionbloomfilter.{thriftscala => blm}
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PublishImpressionBloomFilterSideEffect @Inject() (
bloomFilterClient: ManhattanStoreClient[
blm.ImpressionBloomFilterKey,
blm.ImpressionBloomFilterSeq
]) extends PipelineResultSideEffect[PipelineQuery with HasSeenTweetIds, HasMarshalling]
with PipelineResultSideEffect.Conditionally[
PipelineQuery with HasSeenTweetIds,
HasMarshalling
] {
override val identifier: SideEffectIdentifier =
SideEffectIdentifier("PublishImpressionBloomFilter")
private val SurfaceArea = blm.SurfaceArea.HomeTimeline
override def onlyIf(
query: PipelineQuery with HasSeenTweetIds,
selectedCandidates: Seq[CandidateWithDetails],
remainingCandidates: Seq[CandidateWithDetails],
droppedCandidates: Seq[CandidateWithDetails],
response: HasMarshalling
): Boolean =
query.params.getBoolean(EnableImpressionBloomFilter) && query.seenTweetIds.exists(_.nonEmpty)
def buildEvents(query: PipelineQuery): Option[blm.ImpressionBloomFilterSeq] = {
query.features.flatMap { featureMap =>
val impressionBloomFilterSeq = featureMap.get(ImpressionBloomFilterFeature)
if (impressionBloomFilterSeq.entries.nonEmpty) Some(impressionBloomFilterSeq)
else None
}
}
override def apply(
inputs: PipelineResultSideEffect.Inputs[PipelineQuery with HasSeenTweetIds, HasMarshalling]
): Stitch[Unit] = {
buildEvents(inputs.query)
.map { updatedBloomFilterSeq =>
bloomFilterClient.write(
blm.ImpressionBloomFilterKey(inputs.query.getRequiredUserId, SurfaceArea),
updatedBloomFilterSeq)
}.getOrElse(Stitch.Unit)
}
override val alerts = Seq(
HomeMixerAlertConfig.BusinessHours.defaultSuccessRateAlert(99.8)
)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/side_effect/TruncateTimelinesPersistenceStoreSideEffect.scala | package com.twitter.home_mixer.functional_component.side_effect
import com.twitter.home_mixer.model.HomeFeatures.PersistenceEntriesFeature
import com.twitter.home_mixer.model.request.FollowingProduct
import com.twitter.home_mixer.model.request.ForYouProduct
import com.twitter.home_mixer.param.HomeGlobalParams.TimelinesPersistenceStoreMaxEntriesPerClient
import com.twitter.home_mixer.service.HomeMixerAlertConfig
import com.twitter.product_mixer.core.functional_component.side_effect.PipelineResultSideEffect
import com.twitter.product_mixer.core.model.common.identifier.SideEffectIdentifier
import com.twitter.product_mixer.core.model.marshalling.response.urt.Timeline
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
import com.twitter.timelinemixer.clients.persistence.TimelineResponseBatchesClient
import com.twitter.timelinemixer.clients.persistence.TimelineResponseV3
import com.twitter.timelineservice.model.TimelineQuery
import com.twitter.timelineservice.model.core.TimelineKind
import javax.inject.Inject
import javax.inject.Singleton
/**
* Side effect that truncates entries in the Timelines Persistence store
* based on the number of entries per client.
*/
@Singleton
class TruncateTimelinesPersistenceStoreSideEffect @Inject() (
timelineResponseBatchesClient: TimelineResponseBatchesClient[TimelineResponseV3])
extends PipelineResultSideEffect[PipelineQuery, Timeline] {
override val identifier: SideEffectIdentifier =
SideEffectIdentifier("TruncateTimelinesPersistenceStore")
def getResponsesToDelete(query: PipelineQuery): Seq[TimelineResponseV3] = {
val responses =
query.features.map(_.getOrElse(PersistenceEntriesFeature, Seq.empty)).toSeq.flatten
val responsesByClient = responses.groupBy(_.clientPlatform).values.toSeq
val maxEntriesPerClient = query.params(TimelinesPersistenceStoreMaxEntriesPerClient)
responsesByClient.flatMap {
_.sortBy(_.servedTime.inMilliseconds)
.foldRight((Seq.empty[TimelineResponseV3], maxEntriesPerClient)) {
case (response, (responsesToDelete, remainingCap)) =>
if (remainingCap > 0) (responsesToDelete, remainingCap - response.entries.size)
else (response +: responsesToDelete, remainingCap)
} match { case (responsesToDelete, _) => responsesToDelete }
}
}
final override def apply(
inputs: PipelineResultSideEffect.Inputs[PipelineQuery, Timeline]
): Stitch[Unit] = {
val timelineKind = inputs.query.product match {
case FollowingProduct => TimelineKind.homeLatest
case ForYouProduct => TimelineKind.home
case other => throw new UnsupportedOperationException(s"Unknown product: $other")
}
val timelineQuery = TimelineQuery(id = inputs.query.getRequiredUserId, kind = timelineKind)
val responsesToDelete = getResponsesToDelete(inputs.query)
if (responsesToDelete.nonEmpty)
Stitch.callFuture(timelineResponseBatchesClient.delete(timelineQuery, responsesToDelete))
else Stitch.Unit
}
override val alerts = Seq(
HomeMixerAlertConfig.BusinessHours.defaultSuccessRateAlert(99.8)
)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/side_effect/UpdateLastNonPollingTimeSideEffect.scala | package com.twitter.home_mixer.functional_component.side_effect
import com.twitter.home_mixer.model.HomeFeatures.FollowingLastNonPollingTimeFeature
import com.twitter.home_mixer.model.HomeFeatures.NonPollingTimesFeature
import com.twitter.home_mixer.model.HomeFeatures.PollingFeature
import com.twitter.home_mixer.model.request.DeviceContext
import com.twitter.home_mixer.model.request.HasDeviceContext
import com.twitter.home_mixer.model.request.FollowingProduct
import com.twitter.home_mixer.service.HomeMixerAlertConfig
import com.twitter.product_mixer.component_library.side_effect.UserSessionStoreUpdateSideEffect
import com.twitter.product_mixer.core.model.common.identifier.SideEffectIdentifier
import com.twitter.product_mixer.core.model.marshalling.HasMarshalling
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.timelineservice.model.util.FinagleRequestContext
import com.twitter.user_session_store.ReadWriteUserSessionStore
import com.twitter.user_session_store.WriteRequest
import com.twitter.user_session_store.thriftscala.NonPollingTimestamps
import com.twitter.user_session_store.thriftscala.UserSessionField
import com.twitter.util.Time
import javax.inject.Inject
import javax.inject.Singleton
/**
* Side effect that updates the User Session Store (Manhattan) with the timestamps of non polling requests.
*/
@Singleton
class UpdateLastNonPollingTimeSideEffect[
Query <: PipelineQuery with HasDeviceContext,
ResponseType <: HasMarshalling] @Inject() (
override val userSessionStore: ReadWriteUserSessionStore)
extends UserSessionStoreUpdateSideEffect[
WriteRequest,
Query,
ResponseType
] {
private val MaxNonPollingTimes = 10
override val identifier: SideEffectIdentifier = SideEffectIdentifier("UpdateLastNonPollingTime")
/**
* When the request is non polling and is not a background fetch request, update
* the list of non polling timestamps with the timestamp of the current request
*/
override def buildWriteRequest(query: Query): Option[WriteRequest] = {
val isBackgroundFetch = query.deviceContext
.exists(_.requestContextValue.contains(DeviceContext.RequestContext.BackgroundFetch))
if (!query.features.exists(_.getOrElse(PollingFeature, false)) && !isBackgroundFetch) {
val fields = Seq(UserSessionField.NonPollingTimestamps(makeLastNonPollingTimestamps(query)))
Some(WriteRequest(query.getRequiredUserId, fields))
} else None
}
override val alerts = Seq(
HomeMixerAlertConfig.BusinessHours.defaultSuccessRateAlert(99.96)
)
private def makeLastNonPollingTimestamps(query: Query): NonPollingTimestamps = {
val priorNonPollingTimestamps =
query.features.map(_.getOrElse(NonPollingTimesFeature, Seq.empty)).toSeq.flatten
val lastNonPollingTimeMs =
FinagleRequestContext.default.requestStartTime.get.getOrElse(Time.now).inMillis
val followingLastNonPollingTime = query.features
.flatMap(features => features.getOrElse(FollowingLastNonPollingTimeFeature, None))
.map(_.inMillis)
NonPollingTimestamps(
nonPollingTimestampsMs =
(lastNonPollingTimeMs +: priorNonPollingTimestamps).take(MaxNonPollingTimes),
mostRecentHomeLatestNonPollingTimestampMs =
if (query.product == FollowingProduct) Some(lastNonPollingTimeMs)
else followingLastNonPollingTime
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/side_effect/UpdateTimelinesPersistenceStoreSideEffect.scala | package com.twitter.home_mixer.functional_component.side_effect
import com.twitter.home_mixer.model.HomeFeatures._
import com.twitter.home_mixer.model.request.FollowingProduct
import com.twitter.home_mixer.model.request.ForYouProduct
import com.twitter.home_mixer.model.HomeFeatures.IsTweetPreviewFeature
import com.twitter.home_mixer.service.HomeMixerAlertConfig
import com.twitter.product_mixer.component_library.pipeline.candidate.who_to_follow_module.WhoToFollowCandidateDecorator
import com.twitter.product_mixer.component_library.pipeline.candidate.who_to_subscribe_module.WhoToSubscribeCandidateDecorator
import com.twitter.product_mixer.core.feature.featuremap.FeatureMap
import com.twitter.product_mixer.core.functional_component.side_effect.PipelineResultSideEffect
import com.twitter.product_mixer.core.model.common.identifier.SideEffectIdentifier
import com.twitter.product_mixer.core.model.common.presentation.ItemCandidateWithDetails
import com.twitter.product_mixer.core.model.common.presentation.ModuleCandidateWithDetails
import com.twitter.product_mixer.core.model.marshalling.response.urt.AddEntriesTimelineInstruction
import com.twitter.product_mixer.core.model.marshalling.response.urt.ReplaceEntryTimelineInstruction
import com.twitter.product_mixer.core.model.marshalling.response.urt.ShowCoverInstruction
import com.twitter.product_mixer.core.model.marshalling.response.urt.Timeline
import com.twitter.product_mixer.core.model.marshalling.response.urt.TimelineModule
import com.twitter.product_mixer.core.model.marshalling.response.urt.item.tweet.TweetItem
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.stitch.Stitch
import com.twitter.timelinemixer.clients.persistence.EntryWithItemIds
import com.twitter.timelinemixer.clients.persistence.ItemIds
import com.twitter.timelinemixer.clients.persistence.TimelineResponseBatchesClient
import com.twitter.timelinemixer.clients.persistence.TimelineResponseV3
import com.twitter.timelines.persistence.thriftscala.TweetScoreV1
import com.twitter.timelines.persistence.{thriftscala => persistence}
import com.twitter.timelineservice.model.TimelineQuery
import com.twitter.timelineservice.model.TimelineQueryOptions
import com.twitter.timelineservice.model.TweetScore
import com.twitter.timelineservice.model.core.TimelineKind
import com.twitter.timelineservice.model.rich.EntityIdType
import com.twitter.util.Time
import com.twitter.{timelineservice => tls}
import javax.inject.Inject
import javax.inject.Singleton
object UpdateTimelinesPersistenceStoreSideEffect {
val EmptyItemIds = ItemIds(
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None)
}
/**
* Side effect that updates the Timelines Persistence Store (Manhattan) with the entries being returned.
*/
@Singleton
class UpdateTimelinesPersistenceStoreSideEffect @Inject() (
timelineResponseBatchesClient: TimelineResponseBatchesClient[TimelineResponseV3])
extends PipelineResultSideEffect[PipelineQuery, Timeline] {
override val identifier: SideEffectIdentifier =
SideEffectIdentifier("UpdateTimelinesPersistenceStore")
final override def apply(
inputs: PipelineResultSideEffect.Inputs[PipelineQuery, Timeline]
): Stitch[Unit] = {
if (inputs.response.instructions.nonEmpty) {
val timelineKind = inputs.query.product match {
case FollowingProduct => TimelineKind.homeLatest
case ForYouProduct => TimelineKind.home
case other => throw new UnsupportedOperationException(s"Unknown product: $other")
}
val timelineQuery = TimelineQuery(
id = inputs.query.getRequiredUserId,
kind = timelineKind,
options = TimelineQueryOptions(
contextualUserId = inputs.query.getOptionalUserId,
deviceContext = tls.DeviceContext.empty.copy(
userAgent = inputs.query.clientContext.userAgent,
clientAppId = inputs.query.clientContext.appId)
)
)
val tweetIdToItemCandidateMap: Map[Long, ItemCandidateWithDetails] =
inputs.selectedCandidates.flatMap {
case item: ItemCandidateWithDetails if item.candidate.id.isInstanceOf[Long] =>
Seq((item.candidateIdLong, item))
case module: ModuleCandidateWithDetails
if module.candidates.headOption.exists(_.candidate.id.isInstanceOf[Long]) =>
module.candidates.map(item => (item.candidateIdLong, item))
case _ => Seq.empty
}.toMap
val entries = inputs.response.instructions.collect {
case AddEntriesTimelineInstruction(entries) =>
entries.collect {
// includes tweets, tweet previews, and promoted tweets
case entry: TweetItem if entry.sortIndex.isDefined => {
Seq(
buildTweetEntryWithItemIds(
tweetIdToItemCandidateMap(entry.id),
entry.sortIndex.get
))
}
// tweet conversation modules are flattened to individual tweets in the persistence store
case module: TimelineModule
if module.sortIndex.isDefined && module.items.headOption.exists(
_.item.isInstanceOf[TweetItem]) =>
module.items.map { item =>
buildTweetEntryWithItemIds(
tweetIdToItemCandidateMap(item.item.id.asInstanceOf[Long]),
module.sortIndex.get)
}
case module: TimelineModule
if module.sortIndex.isDefined && module.entryNamespace.toString == WhoToFollowCandidateDecorator.EntryNamespaceString =>
val userIds = module.items
.map(item =>
UpdateTimelinesPersistenceStoreSideEffect.EmptyItemIds.copy(userId =
Some(item.item.id.asInstanceOf[Long])))
Seq(
EntryWithItemIds(
entityIdType = EntityIdType.WhoToFollow,
sortIndex = module.sortIndex.get,
size = module.items.size.toShort,
itemIds = Some(userIds)
))
case module: TimelineModule
if module.sortIndex.isDefined && module.entryNamespace.toString == WhoToSubscribeCandidateDecorator.EntryNamespaceString =>
val userIds = module.items
.map(item =>
UpdateTimelinesPersistenceStoreSideEffect.EmptyItemIds.copy(userId =
Some(item.item.id.asInstanceOf[Long])))
Seq(
EntryWithItemIds(
entityIdType = EntityIdType.WhoToSubscribe,
sortIndex = module.sortIndex.get,
size = module.items.size.toShort,
itemIds = Some(userIds)
))
}.flatten
case ShowCoverInstruction(cover) =>
Seq(
EntryWithItemIds(
entityIdType = EntityIdType.Prompt,
sortIndex = cover.sortIndex.get,
size = 1,
itemIds = None
)
)
case ReplaceEntryTimelineInstruction(entry) =>
val namespaceLength = TweetItem.TweetEntryNamespace.toString.length
Seq(
EntryWithItemIds(
entityIdType = EntityIdType.Tweet,
sortIndex = entry.sortIndex.get,
size = 1,
itemIds = Some(
Seq(
ItemIds(
tweetId =
entry.entryIdToReplace.map(e => e.substring(namespaceLength + 1).toLong),
sourceTweetId = None,
quoteTweetId = None,
sourceAuthorId = None,
quoteAuthorId = None,
inReplyToTweetId = None,
inReplyToAuthorId = None,
semanticCoreId = None,
articleId = None,
hasRelevancePrompt = None,
promptData = None,
tweetScore = None,
entryIdToReplace = entry.entryIdToReplace,
tweetReactiveData = None,
userId = None
)
))
)
)
}.flatten
val response = TimelineResponseV3(
clientPlatform = timelineQuery.clientPlatform,
servedTime = Time.now,
requestType = requestTypeFromQuery(inputs.query),
entries = entries)
Stitch.callFuture(timelineResponseBatchesClient.insertResponse(timelineQuery, response))
} else Stitch.Unit
}
override val alerts = Seq(
HomeMixerAlertConfig.BusinessHours.defaultSuccessRateAlert(99.8)
)
private def buildTweetEntryWithItemIds(
candidate: ItemCandidateWithDetails,
sortIndex: Long
): EntryWithItemIds = {
val features = candidate.features
val sourceAuthorId =
if (features.getOrElse(IsRetweetFeature, false)) features.getOrElse(SourceUserIdFeature, None)
else features.getOrElse(AuthorIdFeature, None)
val quoteAuthorId =
if (features.getOrElse(QuotedTweetIdFeature, None).nonEmpty)
features.getOrElse(SourceUserIdFeature, None)
else None
val tweetScore = features.getOrElse(ScoreFeature, None).map { score =>
TweetScore.fromThrift(persistence.TweetScore.TweetScoreV1(TweetScoreV1(score)))
}
val itemIds = ItemIds(
tweetId = Some(candidate.candidateIdLong),
sourceTweetId = features.getOrElse(SourceTweetIdFeature, None),
quoteTweetId = features.getOrElse(QuotedTweetIdFeature, None),
sourceAuthorId = sourceAuthorId,
quoteAuthorId = quoteAuthorId,
inReplyToTweetId = features.getOrElse(InReplyToTweetIdFeature, None),
inReplyToAuthorId = features.getOrElse(DirectedAtUserIdFeature, None),
semanticCoreId = features.getOrElse(SemanticCoreIdFeature, None),
articleId = None,
hasRelevancePrompt = None,
promptData = None,
tweetScore = tweetScore,
entryIdToReplace = None,
tweetReactiveData = None,
userId = None
)
val isPreview = features.getOrElse(IsTweetPreviewFeature, default = false)
val entityType = if (isPreview) EntityIdType.TweetPreview else EntityIdType.Tweet
EntryWithItemIds(
entityIdType = entityType,
sortIndex = sortIndex,
size = 1.toShort,
itemIds = Some(Seq(itemIds))
)
}
private def requestTypeFromQuery(query: PipelineQuery): persistence.RequestType = {
val features = query.features.getOrElse(FeatureMap.empty)
val featureToRequestType = Seq(
(PollingFeature, persistence.RequestType.Polling),
(GetInitialFeature, persistence.RequestType.Initial),
(GetNewerFeature, persistence.RequestType.Newer),
(GetMiddleFeature, persistence.RequestType.Middle),
(GetOlderFeature, persistence.RequestType.Older)
)
featureToRequestType
.collectFirst {
case (feature, requestType) if features.getOrElse(feature, false) => requestType
}.getOrElse(persistence.RequestType.Other)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/request/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request",
"home-mixer/thrift/src/main/thrift:thrift-scala",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/functional_component/marshaller/request",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/common",
],
exports = [
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request",
"home-mixer/thrift/src/main/thrift:thrift-scala",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/functional_component/marshaller/request",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/common",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/request/DeviceContextUnmarshaller.scala | package com.twitter.home_mixer.marshaller.request
import com.twitter.home_mixer.model.request.DeviceContext
import com.twitter.home_mixer.{thriftscala => t}
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DeviceContextUnmarshaller @Inject() () {
def apply(deviceContext: t.DeviceContext): DeviceContext = {
DeviceContext(
isPolling = deviceContext.isPolling,
requestContext = deviceContext.requestContext,
latestControlAvailable = deviceContext.latestControlAvailable,
autoplayEnabled = deviceContext.autoplayEnabled
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/request/HomeMixerDebugParamsUnmarshaller.scala | package com.twitter.home_mixer.marshaller.request
import com.twitter.home_mixer.model.request.HomeMixerDebugOptions
import com.twitter.home_mixer.{thriftscala => t}
import com.twitter.product_mixer.core.functional_component.marshaller.request.FeatureValueUnmarshaller
import com.twitter.product_mixer.core.model.marshalling.request.DebugParams
import com.twitter.util.Time
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class HomeMixerDebugParamsUnmarshaller @Inject() (
featureValueUnmarshaller: FeatureValueUnmarshaller) {
def apply(debugParams: t.DebugParams): DebugParams = {
DebugParams(
featureOverrides = debugParams.featureOverrides.map { map =>
map.mapValues(featureValueUnmarshaller(_)).toMap
},
debugOptions = debugParams.debugOptions.map { options =>
HomeMixerDebugOptions(
requestTimeOverride = options.requestTimeOverrideMillis.map(Time.fromMilliseconds)
)
}
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/request/HomeMixerProductContextUnmarshaller.scala | package com.twitter.home_mixer.marshaller.request
import com.twitter.home_mixer.model.request.FollowingProductContext
import com.twitter.home_mixer.model.request.ForYouProductContext
import com.twitter.home_mixer.model.request.ListRecommendedUsersProductContext
import com.twitter.home_mixer.model.request.ListTweetsProductContext
import com.twitter.home_mixer.model.request.ScoredTweetsProductContext
import com.twitter.home_mixer.model.request.SubscribedProductContext
import com.twitter.home_mixer.{thriftscala => t}
import com.twitter.product_mixer.core.model.marshalling.request.ProductContext
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class HomeMixerProductContextUnmarshaller @Inject() (
deviceContextUnmarshaller: DeviceContextUnmarshaller) {
def apply(productContext: t.ProductContext): ProductContext = productContext match {
case t.ProductContext.Following(p) =>
FollowingProductContext(
deviceContext = p.deviceContext.map(deviceContextUnmarshaller(_)),
seenTweetIds = p.seenTweetIds,
dspClientContext = p.dspClientContext
)
case t.ProductContext.ForYou(p) =>
ForYouProductContext(
deviceContext = p.deviceContext.map(deviceContextUnmarshaller(_)),
seenTweetIds = p.seenTweetIds,
dspClientContext = p.dspClientContext,
pushToHomeTweetId = p.pushToHomeTweetId
)
case t.ProductContext.ListManagement(p) =>
throw new UnsupportedOperationException(s"This product is no longer used")
case t.ProductContext.ScoredTweets(p) =>
ScoredTweetsProductContext(
deviceContext = p.deviceContext.map(deviceContextUnmarshaller(_)),
seenTweetIds = p.seenTweetIds,
servedTweetIds = p.servedTweetIds,
backfillTweetIds = p.backfillTweetIds
)
case t.ProductContext.ListTweets(p) =>
ListTweetsProductContext(
listId = p.listId,
deviceContext = p.deviceContext.map(deviceContextUnmarshaller(_)),
dspClientContext = p.dspClientContext
)
case t.ProductContext.ListRecommendedUsers(p) =>
ListRecommendedUsersProductContext(
listId = p.listId,
selectedUserIds = p.selectedUserIds,
excludedUserIds = p.excludedUserIds,
listName = p.listName
)
case t.ProductContext.Subscribed(p) =>
SubscribedProductContext(
deviceContext = p.deviceContext.map(deviceContextUnmarshaller(_)),
seenTweetIds = p.seenTweetIds,
)
case t.ProductContext.UnknownUnionField(field) =>
throw new UnsupportedOperationException(s"Unknown display context: ${field.field.name}")
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/request/HomeMixerProductUnmarshaller.scala | package com.twitter.home_mixer.marshaller.request
import com.twitter.home_mixer.model.request.FollowingProduct
import com.twitter.home_mixer.model.request.ForYouProduct
import com.twitter.home_mixer.model.request.ListRecommendedUsersProduct
import com.twitter.home_mixer.model.request.ListTweetsProduct
import com.twitter.home_mixer.model.request.ScoredTweetsProduct
import com.twitter.home_mixer.model.request.SubscribedProduct
import com.twitter.home_mixer.{thriftscala => t}
import com.twitter.product_mixer.core.model.marshalling.request.Product
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class HomeMixerProductUnmarshaller @Inject() () {
def apply(product: t.Product): Product = product match {
case t.Product.Following => FollowingProduct
case t.Product.ForYou => ForYouProduct
case t.Product.ListManagement =>
throw new UnsupportedOperationException(s"This product is no longer used")
case t.Product.ScoredTweets => ScoredTweetsProduct
case t.Product.ListTweets => ListTweetsProduct
case t.Product.ListRecommendedUsers => ListRecommendedUsersProduct
case t.Product.Subscribed => SubscribedProduct
case t.Product.EnumUnknownProduct(value) =>
throw new UnsupportedOperationException(s"Unknown product: $value")
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/request/HomeMixerRequestUnmarshaller.scala | package com.twitter.home_mixer.marshaller.request
import com.twitter.home_mixer.model.request.HomeMixerRequest
import com.twitter.home_mixer.{thriftscala => t}
import com.twitter.product_mixer.core.functional_component.marshaller.request.ClientContextUnmarshaller
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class HomeMixerRequestUnmarshaller @Inject() (
clientContextUnmarshaller: ClientContextUnmarshaller,
homeProductUnmarshaller: HomeMixerProductUnmarshaller,
homeProductContextUnmarshaller: HomeMixerProductContextUnmarshaller,
homeDebugParamsUnmarshaller: HomeMixerDebugParamsUnmarshaller) {
def apply(homeRequest: t.HomeMixerRequest): HomeMixerRequest = {
HomeMixerRequest(
clientContext = clientContextUnmarshaller(homeRequest.clientContext),
product = homeProductUnmarshaller(homeRequest.product),
productContext = homeRequest.productContext.map(homeProductContextUnmarshaller(_)),
// Avoid de-serializing cursors in the request unmarshaller. The unmarshaller should never
// fail, which is often a possibility when trying to de-serialize a cursor. Cursors can also
// be product-specific and more appropriately handled in individual product pipelines.
serializedRequestCursor = homeRequest.cursor,
maxResults = homeRequest.maxResults,
debugParams = homeRequest.debugParams.map(homeDebugParamsUnmarshaller(_)),
homeRequestParam = false
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timeline_logging/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/model/presentation/urt",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/pipeline/candidate/who_to_follow_module",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/marshalling/response/urt/item",
"src/thrift/com/twitter/timelines/timeline_logging:thrift-scala",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timeline_logging/PromotedTweetDetailsMarshaller.scala | package com.twitter.home_mixer.marshaller.timeline_logging
import com.twitter.product_mixer.core.model.marshalling.response.urt.item.tweet.TweetItem
import com.twitter.timelines.timeline_logging.{thriftscala => thriftlog}
object PromotedTweetDetailsMarshaller {
def apply(entry: TweetItem, position: Int): thriftlog.PromotedTweetDetails = {
thriftlog.PromotedTweetDetails(
advertiserId = Some(entry.promotedMetadata.map(_.advertiserId).getOrElse(0L)),
insertPosition = Some(position),
impressionId = entry.promotedMetadata.flatMap(_.impressionString)
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timeline_logging/TweetDetailsMarshaller.scala | package com.twitter.home_mixer.marshaller.timeline_logging
import com.twitter.home_mixer.model.HomeFeatures.AuthorIdFeature
import com.twitter.home_mixer.model.HomeFeatures.SourceTweetIdFeature
import com.twitter.home_mixer.model.HomeFeatures.SourceUserIdFeature
import com.twitter.home_mixer.model.HomeFeatures.SuggestTypeFeature
import com.twitter.product_mixer.component_library.model.presentation.urt.UrtItemPresentation
import com.twitter.product_mixer.component_library.model.presentation.urt.UrtModulePresentation
import com.twitter.product_mixer.core.functional_component.marshaller.response.urt.metadata.GeneralContextTypeMarshaller
import com.twitter.product_mixer.core.model.common.presentation.CandidateWithDetails
import com.twitter.product_mixer.core.model.marshalling.response.urt.item.tweet.TweetItem
import com.twitter.product_mixer.core.model.marshalling.response.urt.metadata.ConversationGeneralContextType
import com.twitter.product_mixer.core.model.marshalling.response.urt.metadata.GeneralContext
import com.twitter.product_mixer.core.model.marshalling.response.urt.metadata.TopicContext
import com.twitter.timelines.service.{thriftscala => tst}
import com.twitter.timelines.timeline_logging.{thriftscala => thriftlog}
object TweetDetailsMarshaller {
private val generalContextTypeMarshaller = new GeneralContextTypeMarshaller()
def apply(entry: TweetItem, candidate: CandidateWithDetails): thriftlog.TweetDetails = {
val socialContext = candidate.presentation.flatMap {
case _ @UrtItemPresentation(timelineItem: TweetItem, _) => timelineItem.socialContext
case _ @UrtModulePresentation(timelineModule) =>
timelineModule.items.head.item match {
case timelineItem: TweetItem => timelineItem.socialContext
case _ => Some(ConversationGeneralContextType)
}
}
val socialContextType = socialContext match {
case Some(GeneralContext(contextType, _, _, _, _)) =>
Some(generalContextTypeMarshaller(contextType).value.toShort)
case Some(TopicContext(_, _)) => Some(tst.ContextType.Topic.value.toShort)
case _ => None
}
thriftlog.TweetDetails(
sourceTweetId = candidate.features.getOrElse(SourceTweetIdFeature, None),
socialContextType = socialContextType,
suggestType = candidate.features.getOrElse(SuggestTypeFeature, None).map(_.name),
authorId = candidate.features.getOrElse(AuthorIdFeature, None),
sourceAuthorId = candidate.features.getOrElse(SourceUserIdFeature, None)
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timeline_logging/WhoToFollowDetailsMarshaller.scala | package com.twitter.home_mixer.marshaller.timeline_logging
import com.twitter.product_mixer.core.model.common.presentation.ItemCandidateWithDetails
import com.twitter.product_mixer.core.model.marshalling.response.urt.item.user.UserItem
import com.twitter.timelines.timeline_logging.{thriftscala => thriftlog}
object WhoToFollowDetailsMarshaller {
def apply(entry: UserItem, candidate: ItemCandidateWithDetails): thriftlog.WhoToFollowDetails =
thriftlog.WhoToFollowDetails(
enableReactiveBlending = entry.enableReactiveBlending,
impressionId = entry.promotedMetadata.flatMap(_.impressionString),
advertiserId = entry.promotedMetadata.map(_.advertiserId)
)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timelines/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/model/cursor",
"src/thrift/com/twitter/timelineservice:thrift-scala",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timelines/ChronologicalCursorMarshaller.scala | package com.twitter.home_mixer.marshaller.timelines
import com.twitter.product_mixer.component_library.model.cursor.UrtOrderedCursor
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.BottomCursor
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.GapCursor
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.TopCursor
import com.twitter.timelines.service.{thriftscala => t}
object ChronologicalCursorMarshaller {
def apply(cursor: UrtOrderedCursor): Option[t.ChronologicalCursor] = {
cursor.cursorType match {
case Some(TopCursor) => Some(t.ChronologicalCursor(bottom = cursor.id))
case Some(BottomCursor) => Some(t.ChronologicalCursor(top = cursor.id))
case Some(GapCursor) =>
Some(t.ChronologicalCursor(top = cursor.id, bottom = cursor.gapBoundaryId))
case _ => None
}
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timelines/ChronologicalCursorUnmarshaller.scala | package com.twitter.home_mixer.marshaller.timelines
import com.twitter.product_mixer.component_library.model.cursor.UrtOrderedCursor
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.BottomCursor
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.GapCursor
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.TopCursor
import com.twitter.timelines.service.{thriftscala => t}
object ChronologicalCursorUnmarshaller {
def apply(requestCursor: t.RequestCursor): Option[UrtOrderedCursor] = {
requestCursor match {
case t.RequestCursor.ChronologicalCursor(cursor) =>
(cursor.top, cursor.bottom) match {
case (Some(top), None) =>
Some(UrtOrderedCursor(top, cursor.top, Some(BottomCursor)))
case (None, Some(bottom)) =>
Some(UrtOrderedCursor(bottom, cursor.bottom, Some(TopCursor)))
case (Some(top), Some(bottom)) =>
Some(UrtOrderedCursor(top, cursor.top, Some(GapCursor), cursor.bottom))
case _ => None
}
case _ => None
}
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timelines/DeviceContextMarshaller.scala | package com.twitter.home_mixer.marshaller.timelines
import com.twitter.home_mixer.model.request.DeviceContext
import com.twitter.product_mixer.core.model.marshalling.request.ClientContext
import com.twitter.timelineservice.{thriftscala => t}
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DeviceContextMarshaller @Inject() () {
def apply(deviceContext: DeviceContext, clientContext: ClientContext): t.DeviceContext = {
t.DeviceContext(
countryCode = clientContext.countryCode,
languageCode = clientContext.languageCode,
clientAppId = clientContext.appId,
ipAddress = clientContext.ipAddress,
guestId = clientContext.guestId,
userAgent = clientContext.userAgent,
deviceId = clientContext.deviceId,
isPolling = deviceContext.isPolling,
requestContext = deviceContext.requestContext,
referrer = None,
tfeAuthHeader = None,
mobileDeviceId = clientContext.mobileDeviceId,
isSessionStart = None,
latestControlAvailable = deviceContext.latestControlAvailable,
guestIdMarketing = clientContext.guestIdMarketing,
isInternalOrTwoffice = clientContext.isTwoffice,
guestIdAds = clientContext.guestIdAds,
isUrtRequest = Some(true)
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timelines/RecommendedUsersCursorUnmarshaller.scala | package com.twitter.home_mixer.marshaller.timelines
import com.twitter.product_mixer.component_library.model.cursor.UrtUnorderedExcludeIdsCursor
import com.twitter.timelines.service.{thriftscala => t}
import com.twitter.util.Time
object RecommendedUsersCursorUnmarshaller {
def apply(requestCursor: t.RequestCursor): Option[UrtUnorderedExcludeIdsCursor] = {
requestCursor match {
case t.RequestCursor.RecommendedUsersCursor(cursor) =>
Some(
UrtUnorderedExcludeIdsCursor(
initialSortIndex = cursor.minSortIndex.getOrElse(Time.now.inMilliseconds),
excludedIds = cursor.previouslyRecommendedUserIds
))
case _ => None
}
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timelines/TimelineServiceCursorMarshaller.scala | package com.twitter.home_mixer.marshaller.timelines
import com.twitter.product_mixer.component_library.model.cursor.UrtOrderedCursor
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.BottomCursor
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.GapCursor
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.TopCursor
import com.twitter.timelineservice.{thriftscala => t}
object TimelineServiceCursorMarshaller {
def apply(cursor: UrtOrderedCursor): Option[t.Cursor2] = {
val id = cursor.id.map(_.toString)
val gapBoundaryId = cursor.gapBoundaryId.map(_.toString)
cursor.cursorType match {
case Some(TopCursor) => Some(t.Cursor2(bottom = id))
case Some(BottomCursor) => Some(t.Cursor2(top = id))
case Some(GapCursor) => Some(t.Cursor2(top = id, bottom = gapBoundaryId))
case _ => None
}
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/marshaller/timelines/TopicContextFunctionalityTypeUnmarshaller.scala | package com.twitter.home_mixer.marshaller.timelines
import com.twitter.product_mixer.core.model.marshalling.response.urt.metadata.BasicTopicContextFunctionalityType
import com.twitter.product_mixer.core.model.marshalling.response.urt.metadata.RecWithEducationTopicContextFunctionalityType
import com.twitter.product_mixer.core.model.marshalling.response.urt.metadata.RecommendationTopicContextFunctionalityType
import com.twitter.product_mixer.core.model.marshalling.response.urt.metadata.TopicContextFunctionalityType
import com.twitter.timelines.render.{thriftscala => urt}
object TopicContextFunctionalityTypeUnmarshaller {
def apply(
topicContextFunctionalityType: urt.TopicContextFunctionalityType
): TopicContextFunctionalityType = topicContextFunctionalityType match {
case urt.TopicContextFunctionalityType.Basic => BasicTopicContextFunctionalityType
case urt.TopicContextFunctionalityType.Recommendation =>
RecommendationTopicContextFunctionalityType
case urt.TopicContextFunctionalityType.RecWithEducation =>
RecWithEducationTopicContextFunctionalityType
case urt.TopicContextFunctionalityType.EnumUnknownTopicContextFunctionalityType(field) =>
throw new UnsupportedOperationException(s"Unknown topic context functionality type: $field")
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/candidate_source",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request",
"home-mixer/thrift/src/main/thrift:thrift-scala",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/model/query/ads",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/premarshaller/urt/builder",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/feature/datarecord",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/pipeline",
"src/java/com/twitter/ml/api:api-base",
"src/java/com/twitter/ml/api/constant",
"src/scala/com/twitter/ml/api:api-base",
"src/scala/com/twitter/timelines/prediction/features/common",
"src/scala/com/twitter/timelines/prediction/features/recap",
"src/scala/com/twitter/timelines/prediction/features/request_context",
"src/thrift/com/twitter/escherbird:tweet-annotation-scala",
"src/thrift/com/twitter/search:earlybird-scala",
"src/thrift/com/twitter/timelines/conversation_features:conversation_features-scala",
"src/thrift/com/twitter/timelines/impression:thrift-scala",
"src/thrift/com/twitter/timelines/impression_bloom_filter:thrift-scala",
"src/thrift/com/twitter/timelinescorer/common/scoredtweetcandidate:thrift-scala",
"src/thrift/com/twitter/tweetypie:tweet-scala",
"timelinemixer/common/src/main/scala/com/twitter/timelinemixer/clients/manhattan",
"timelinemixer/common/src/main/scala/com/twitter/timelinemixer/clients/persistence",
"timelinemixer/server/src/main/scala/com/twitter/timelinemixer/injection/model/candidate",
"topic-social-proof/server/src/main/thrift:thrift-scala",
"tweetconvosvc/common/src/main/thrift/com/twitter/tweetconvosvc/tweet_ancestor:thrift-scala",
],
exports = [
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/model/cursor",
"product-mixer/component-library/src/main/scala/com/twitter/product_mixer/component_library/model/query/ads",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/feature/datarecord",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/pipeline",
"src/thrift/com/twitter/timelines/impression:thrift-scala",
"src/thrift/com/twitter/timelinescorer/common/scoredtweetcandidate:thrift-scala",
"tweetconvosvc/common/src/main/thrift/com/twitter/tweetconvosvc/tweet_ancestor:thrift-scala",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/ClearCacheIncludeInstruction.scala | package com.twitter.home_mixer.model
import com.twitter.home_mixer.model.request.DeviceContext.RequestContext
import com.twitter.home_mixer.model.request.HasDeviceContext
import com.twitter.product_mixer.component_library.premarshaller.urt.builder.IncludeInstruction
import com.twitter.product_mixer.core.model.marshalling.response.urt.TimelineEntry
import com.twitter.product_mixer.core.model.marshalling.response.urt.TimelineModule
import com.twitter.product_mixer.core.model.marshalling.response.urt.item.tweet.TweetItem
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.timelines.configapi.FSBoundedParam
import com.twitter.timelines.configapi.FSParam
/**
* Include a clear cache timeline instruction when we satisfy these criteria:
* - Request Provenance is "pull to refresh"
* - Atleast N non-ad tweet entries in the response
*
* This is to ensure that we have sufficient new content to justify jumping users to the
* top of the new timelines response and don't add unnecessary load to backend systems
*/
case class ClearCacheIncludeInstruction(
enableParam: FSParam[Boolean],
minEntriesParam: FSBoundedParam[Int])
extends IncludeInstruction[PipelineQuery with HasDeviceContext] {
override def apply(
query: PipelineQuery with HasDeviceContext,
entries: Seq[TimelineEntry]
): Boolean = {
val enabled = query.params(enableParam)
val ptr =
query.deviceContext.flatMap(_.requestContextValue).contains(RequestContext.PullToRefresh)
val minTweets = query.params(minEntriesParam) <= entries.collect {
case item: TweetItem if item.promotedMetadata.isEmpty => 1
case module: TimelineModule if module.items.head.item.isInstanceOf[TweetItem] =>
module.items.size
}.sum
enabled && ptr && minTweets
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/ContentFeatures.scala | package com.twitter.home_mixer.model
import com.twitter.escherbird.{thriftscala => esb}
import com.twitter.search.common.features.{thriftscala => sc}
import com.twitter.tweetypie.{thriftscala => tp}
object ContentFeatures {
val Empty: ContentFeatures = ContentFeatures(
0.toShort,
false,
0.toShort,
0.toShort,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None
)
def fromThrift(ebFeatures: sc.ThriftTweetFeatures): ContentFeatures =
ContentFeatures(
length = ebFeatures.tweetLength.getOrElse(0).toShort,
hasQuestion = ebFeatures.hasQuestion.getOrElse(false),
numCaps = ebFeatures.numCaps.getOrElse(0).toShort,
numWhiteSpaces = ebFeatures.numWhitespaces.getOrElse(0).toShort,
numNewlines = ebFeatures.numNewlines,
videoDurationMs = ebFeatures.videoDurationMs,
bitRate = ebFeatures.bitRate,
aspectRatioNum = ebFeatures.aspectRatioNum,
aspectRatioDen = ebFeatures.aspectRatioDen,
widths = ebFeatures.widths.map(_.map(_.toShort)),
heights = ebFeatures.heights.map(_.map(_.toShort)),
resizeMethods = ebFeatures.resizeMethods.map(_.map(_.toShort)),
numMediaTags = ebFeatures.numMediaTags.map(_.toShort),
mediaTagScreenNames = ebFeatures.mediaTagScreenNames,
emojiTokens = ebFeatures.emojiTokens.map(_.toSet),
emoticonTokens = ebFeatures.emoticonTokens.map(_.toSet),
faceAreas = ebFeatures.faceAreas,
dominantColorRed = ebFeatures.dominantColorRed,
dominantColorBlue = ebFeatures.dominantColorBlue,
dominantColorGreen = ebFeatures.dominantColorGreen,
numColors = ebFeatures.numColors.map(_.toShort),
stickerIds = ebFeatures.stickerIds,
mediaOriginProviders = ebFeatures.mediaOriginProviders,
isManaged = ebFeatures.isManaged,
is360 = ebFeatures.is360,
viewCount = ebFeatures.viewCount,
isMonetizable = ebFeatures.isMonetizable,
isEmbeddable = ebFeatures.isEmbeddable,
hasSelectedPreviewImage = ebFeatures.hasSelectedPreviewImage,
hasTitle = ebFeatures.hasTitle,
hasDescription = ebFeatures.hasDescription,
hasVisitSiteCallToAction = ebFeatures.hasVisitSiteCallToAction,
hasAppInstallCallToAction = ebFeatures.hasAppInstallCallToAction,
hasWatchNowCallToAction = ebFeatures.hasWatchNowCallToAction,
dominantColorPercentage = ebFeatures.dominantColorPercentage,
posUnigrams = ebFeatures.posUnigrams.map(_.toSet),
posBigrams = ebFeatures.posBigrams.map(_.toSet),
semanticCoreAnnotations = ebFeatures.semanticCoreAnnotations,
tokens = ebFeatures.textTokens.map(_.toSeq),
conversationControl = ebFeatures.conversationControl,
// media and selfThreadMetadata not carried by ThriftTweetFeatures
media = None,
selfThreadMetadata = None
)
}
case class ContentFeatures(
length: Short,
hasQuestion: Boolean,
numCaps: Short,
numWhiteSpaces: Short,
numNewlines: Option[Short],
videoDurationMs: Option[Int],
bitRate: Option[Int],
aspectRatioNum: Option[Short],
aspectRatioDen: Option[Short],
widths: Option[Seq[Short]],
heights: Option[Seq[Short]],
resizeMethods: Option[Seq[Short]],
numMediaTags: Option[Short],
mediaTagScreenNames: Option[Seq[String]],
emojiTokens: Option[Set[String]],
emoticonTokens: Option[Set[String]],
faceAreas: Option[Seq[Int]],
dominantColorRed: Option[Short],
dominantColorBlue: Option[Short],
dominantColorGreen: Option[Short],
numColors: Option[Short],
stickerIds: Option[Seq[Long]],
mediaOriginProviders: Option[Seq[String]],
isManaged: Option[Boolean],
is360: Option[Boolean],
viewCount: Option[Long],
isMonetizable: Option[Boolean],
isEmbeddable: Option[Boolean],
hasSelectedPreviewImage: Option[Boolean],
hasTitle: Option[Boolean],
hasDescription: Option[Boolean],
hasVisitSiteCallToAction: Option[Boolean],
hasAppInstallCallToAction: Option[Boolean],
hasWatchNowCallToAction: Option[Boolean],
media: Option[Seq[tp.MediaEntity]],
dominantColorPercentage: Option[Double],
posUnigrams: Option[Set[String]],
posBigrams: Option[Set[String]],
semanticCoreAnnotations: Option[Seq[esb.TweetEntityAnnotation]],
selfThreadMetadata: Option[tp.SelfThreadMetadata],
tokens: Option[Seq[String]],
conversationControl: Option[tp.ConversationControl],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/GapIncludeInstruction.scala | package com.twitter.home_mixer.model
import com.twitter.home_mixer.functional_component.candidate_source.EarlybirdBottomTweetFeature
import com.twitter.home_mixer.functional_component.candidate_source.EarlybirdResponseTruncatedFeature
import com.twitter.product_mixer.component_library.model.cursor.UrtOrderedCursor
import com.twitter.product_mixer.component_library.premarshaller.urt.builder.IncludeInstruction
import com.twitter.product_mixer.core.model.marshalling.response.urt.TimelineEntry
import com.twitter.product_mixer.core.model.marshalling.response.urt.TimelineModule
import com.twitter.product_mixer.core.model.marshalling.response.urt.item.tweet.TweetItem
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.GapCursor
import com.twitter.product_mixer.core.model.marshalling.response.urt.operation.TopCursor
import com.twitter.product_mixer.core.pipeline.HasPipelineCursor
import com.twitter.product_mixer.core.pipeline.PipelineQuery
/**
* Determine whether to include a Gap Cursor in the response based on whether a timeline
* is truncated because it has more entries than the max response size.
* There are two ways this can happen:
* 1) There are unused entries in Earlybird. This is determined by a flag returned from Earlybird.
* We respect the Earlybird flag only if there are some entries after deduping and filtering
* to ensure that we do not get stuck repeatedly serving gaps which lead to no tweets.
* 2) Ads injection can take the response size over the max count. Goldfinch truncates tweet
* entries in this case. We can check if the bottom tweet from Earlybird is in the response to
* determine if all Earlybird tweets have been used.
*
* While scrolling down to get older tweets (BottomCursor), responses will generally be
* truncated, but we don't want to render a gap cursor there, so we need to ensure we only
* apply the truncation check to newer (TopCursor) or middle (GapCursor) requests.
*
* We return either a Gap Cursor or a Bottom Cursor, but not both, so the include instruction
* for Bottom should be the inverse of Gap.
*/
object GapIncludeInstruction
extends IncludeInstruction[PipelineQuery with HasPipelineCursor[UrtOrderedCursor]] {
override def apply(
query: PipelineQuery with HasPipelineCursor[UrtOrderedCursor],
entries: Seq[TimelineEntry]
): Boolean = {
val wasTruncated = query.features.exists(_.getOrElse(EarlybirdResponseTruncatedFeature, false))
// Get oldest tweet or tweets within oldest conversation module
val tweetEntries = entries.view.reverse
.collectFirst {
case item: TweetItem if item.promotedMetadata.isEmpty => Seq(item.id.toString)
case module: TimelineModule if module.items.head.item.isInstanceOf[TweetItem] =>
module.items.map(_.item.id.toString)
}.toSeq.flatten
val bottomCursor =
query.features.flatMap(_.getOrElse(EarlybirdBottomTweetFeature, None)).map(_.toString)
// Ads truncation happened if we have at least max count entries and bottom tweet is missing
val adsTruncation = query.requestedMaxResults.exists(_ <= entries.size) &&
!bottomCursor.exists(tweetEntries.contains)
query.pipelineCursor.exists(_.cursorType match {
case Some(TopCursor) | Some(GapCursor) =>
(wasTruncated && tweetEntries.nonEmpty) || adsTruncation
case _ => false
})
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/HomeAdsQuery.scala | package com.twitter.home_mixer.model
import com.twitter.adserver.thriftscala.RequestTriggerType
import com.twitter.home_mixer.model.HomeFeatures.GetInitialFeature
import com.twitter.home_mixer.model.HomeFeatures.GetNewerFeature
import com.twitter.home_mixer.model.HomeFeatures.GetOlderFeature
import com.twitter.home_mixer.model.HomeFeatures.PollingFeature
import com.twitter.home_mixer.model.request.HasDeviceContext
import com.twitter.product_mixer.component_library.model.cursor.UrtOrderedCursor
import com.twitter.product_mixer.component_library.model.query.ads.AdsQuery
import com.twitter.product_mixer.core.feature.featuremap.FeatureMap
import com.twitter.product_mixer.core.pipeline.HasPipelineCursor
import com.twitter.product_mixer.core.pipeline.PipelineQuery
/**
* These are for feeds needed for ads only.
*/
trait HomeAdsQuery
extends AdsQuery
with PipelineQuery
with HasDeviceContext
with HasPipelineCursor[UrtOrderedCursor] {
private val featureToRequestTriggerType = Seq(
(GetInitialFeature, RequestTriggerType.Initial),
(GetNewerFeature, RequestTriggerType.Scroll),
(GetOlderFeature, RequestTriggerType.Scroll),
(PollingFeature, RequestTriggerType.AutoRefresh)
)
override val autoplayEnabled: Option[Boolean] = deviceContext.flatMap(_.autoplayEnabled)
override def requestTriggerType: Option[RequestTriggerType] = {
val features = this.features.getOrElse(FeatureMap.empty)
featureToRequestTriggerType.collectFirst {
case (feature, requestType) if features.get(feature) => Some(requestType)
}.flatten
}
override val disableNsfwAvoidance: Option[Boolean] = Some(true)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/HomeFeatures.scala | package com.twitter.home_mixer.model
import com.twitter.core_workflows.user_model.{thriftscala => um}
import com.twitter.dal.personal_data.{thriftjava => pd}
import com.twitter.gizmoduck.{thriftscala => gt}
import com.twitter.home_mixer.{thriftscala => hmt}
import com.twitter.ml.api.constant.SharedFeatures
import com.twitter.product_mixer.component_library.model.candidate.TweetCandidate
import com.twitter.product_mixer.core.feature.Feature
import com.twitter.product_mixer.core.feature.FeatureWithDefaultOnFailure
import com.twitter.product_mixer.core.feature.datarecord.BoolDataRecordCompatible
import com.twitter.product_mixer.core.feature.datarecord.DataRecordFeature
import com.twitter.product_mixer.core.feature.datarecord.DataRecordOptionalFeature
import com.twitter.product_mixer.core.feature.datarecord.DoubleDataRecordCompatible
import com.twitter.product_mixer.core.feature.datarecord.LongDiscreteDataRecordCompatible
import com.twitter.product_mixer.core.model.marshalling.response.urt.metadata.TopicContextFunctionalityType
import com.twitter.product_mixer.core.pipeline.PipelineQuery
import com.twitter.search.common.features.{thriftscala => sc}
import com.twitter.search.earlybird.{thriftscala => eb}
import com.twitter.timelinemixer.clients.manhattan.DismissInfo
import com.twitter.timelinemixer.clients.persistence.TimelineResponseV3
import com.twitter.timelinemixer.injection.model.candidate.AudioSpaceMetaData
import com.twitter.timelines.conversation_features.v1.thriftscala.ConversationFeatures
import com.twitter.timelines.impression.{thriftscala => imp}
import com.twitter.timelines.impressionbloomfilter.{thriftscala => blm}
import com.twitter.timelines.model.UserId
import com.twitter.timelines.prediction.features.common.TimelinesSharedFeatures
import com.twitter.timelines.prediction.features.engagement_features.EngagementDataRecordFeatures
import com.twitter.timelines.prediction.features.recap.RecapFeatures
import com.twitter.timelines.prediction.features.request_context.RequestContextFeatures
import com.twitter.timelines.service.{thriftscala => tst}
import com.twitter.timelineservice.model.FeedbackEntry
import com.twitter.timelineservice.suggests.logging.candidate_tweet_source_id.{thriftscala => cts}
import com.twitter.timelineservice.suggests.{thriftscala => st}
import com.twitter.tsp.{thriftscala => tsp}
import com.twitter.tweetconvosvc.tweet_ancestor.{thriftscala => ta}
import com.twitter.util.Time
object HomeFeatures {
// Candidate Features
object AncestorsFeature extends Feature[TweetCandidate, Seq[ta.TweetAncestor]]
object AudioSpaceMetaDataFeature extends Feature[TweetCandidate, Option[AudioSpaceMetaData]]
object TwitterListIdFeature extends Feature[TweetCandidate, Option[Long]]
/**
* For Retweets, this should refer to the retweeting user. Use [[SourceUserIdFeature]] if you want to know
* who created the Tweet that was retweeted.
*/
object AuthorIdFeature
extends DataRecordOptionalFeature[TweetCandidate, Long]
with LongDiscreteDataRecordCompatible {
override val featureName: String = SharedFeatures.AUTHOR_ID.getFeatureName
override val personalDataTypes: Set[pd.PersonalDataType] = Set(pd.PersonalDataType.UserId)
}
object AuthorIsBlueVerifiedFeature extends Feature[TweetCandidate, Boolean]
object AuthorIsGoldVerifiedFeature extends Feature[TweetCandidate, Boolean]
object AuthorIsGrayVerifiedFeature extends Feature[TweetCandidate, Boolean]
object AuthorIsLegacyVerifiedFeature extends Feature[TweetCandidate, Boolean]
object AuthorIsCreatorFeature extends Feature[TweetCandidate, Boolean]
object AuthorIsProtectedFeature extends Feature[TweetCandidate, Boolean]
object AuthoredByContextualUserFeature extends Feature[TweetCandidate, Boolean]
object CachedCandidatePipelineIdentifierFeature extends Feature[TweetCandidate, Option[String]]
object CandidateSourceIdFeature
extends Feature[TweetCandidate, Option[cts.CandidateTweetSourceId]]
object ConversationFeature extends Feature[TweetCandidate, Option[ConversationFeatures]]
/**
* This field should be set to the focal Tweet's tweetId for all tweets which are expected to
* be rendered in the same convo module. For non-convo module Tweets, this will be
* set to None. Note this is different from how TweetyPie defines ConversationId which is defined
* on all Tweets and points to the root tweet. This feature is used for grouping convo modules together.
*/
object ConversationModuleFocalTweetIdFeature extends Feature[TweetCandidate, Option[Long]]
/**
* This field should always be set to the root Tweet in a conversation for all Tweets. For replies, this will
* point back to the root Tweet. For non-replies, this will be the candidate's Tweet id. This is consistent with
* the TweetyPie definition of ConversationModuleId.
*/
object ConversationModuleIdFeature extends Feature[TweetCandidate, Option[Long]]
object DirectedAtUserIdFeature extends Feature[TweetCandidate, Option[Long]]
object EarlybirdFeature extends Feature[TweetCandidate, Option[sc.ThriftTweetFeatures]]
object EarlybirdScoreFeature extends Feature[TweetCandidate, Option[Double]]
object EarlybirdSearchResultFeature extends Feature[TweetCandidate, Option[eb.ThriftSearchResult]]
object EntityTokenFeature extends Feature[TweetCandidate, Option[String]]
object ExclusiveConversationAuthorIdFeature extends Feature[TweetCandidate, Option[Long]]
object FavoritedByCountFeature
extends DataRecordFeature[TweetCandidate, Double]
with DoubleDataRecordCompatible {
override val featureName: String =
EngagementDataRecordFeatures.InNetworkFavoritesCount.getFeatureName
override val personalDataTypes: Set[pd.PersonalDataType] =
Set(pd.PersonalDataType.CountOfPrivateLikes, pd.PersonalDataType.CountOfPublicLikes)
}
object FavoritedByUserIdsFeature extends Feature[TweetCandidate, Seq[Long]]
object FeedbackHistoryFeature extends Feature[TweetCandidate, Seq[FeedbackEntry]]
object RetweetedByCountFeature
extends DataRecordFeature[TweetCandidate, Double]
with DoubleDataRecordCompatible {
override val featureName: String =
EngagementDataRecordFeatures.InNetworkRetweetsCount.getFeatureName
override val personalDataTypes: Set[pd.PersonalDataType] =
Set(pd.PersonalDataType.CountOfPrivateRetweets, pd.PersonalDataType.CountOfPublicRetweets)
}
object RetweetedByEngagerIdsFeature extends Feature[TweetCandidate, Seq[Long]]
object RepliedByCountFeature
extends DataRecordFeature[TweetCandidate, Double]
with DoubleDataRecordCompatible {
override val featureName: String =
EngagementDataRecordFeatures.InNetworkRepliesCount.getFeatureName
override val personalDataTypes: Set[pd.PersonalDataType] =
Set(pd.PersonalDataType.CountOfPrivateReplies, pd.PersonalDataType.CountOfPublicReplies)
}
object RepliedByEngagerIdsFeature extends Feature[TweetCandidate, Seq[Long]]
object FollowedByUserIdsFeature extends Feature[TweetCandidate, Seq[Long]]
object TopicIdSocialContextFeature extends Feature[TweetCandidate, Option[Long]]
object TopicContextFunctionalityTypeFeature
extends Feature[TweetCandidate, Option[TopicContextFunctionalityType]]
object FromInNetworkSourceFeature extends Feature[TweetCandidate, Boolean]
object FullScoringSucceededFeature extends Feature[TweetCandidate, Boolean]
object HasDisplayedTextFeature extends Feature[TweetCandidate, Boolean]
object InReplyToTweetIdFeature extends Feature[TweetCandidate, Option[Long]]
object InReplyToUserIdFeature extends Feature[TweetCandidate, Option[Long]]
object IsAncestorCandidateFeature extends Feature[TweetCandidate, Boolean]
object IsExtendedReplyFeature
extends DataRecordFeature[TweetCandidate, Boolean]
with BoolDataRecordCompatible {
override val featureName: String = RecapFeatures.IS_EXTENDED_REPLY.getFeatureName
override val personalDataTypes: Set[pd.PersonalDataType] = Set.empty
}
object IsRandomTweetFeature
extends DataRecordFeature[TweetCandidate, Boolean]
with BoolDataRecordCompatible {
override val featureName: String = TimelinesSharedFeatures.IS_RANDOM_TWEET.getFeatureName
override val personalDataTypes: Set[pd.PersonalDataType] = Set.empty
}
object IsReadFromCacheFeature extends Feature[TweetCandidate, Boolean]
object IsRetweetFeature extends Feature[TweetCandidate, Boolean]
object IsRetweetedReplyFeature extends Feature[TweetCandidate, Boolean]
object IsSupportAccountReplyFeature extends Feature[TweetCandidate, Boolean]
object LastScoredTimestampMsFeature extends Feature[TweetCandidate, Option[Long]]
object NonSelfFavoritedByUserIdsFeature extends Feature[TweetCandidate, Seq[Long]]
object NumImagesFeature extends Feature[TweetCandidate, Option[Int]]
object OriginalTweetCreationTimeFromSnowflakeFeature extends Feature[TweetCandidate, Option[Time]]
object PositionFeature extends Feature[TweetCandidate, Option[Int]]
// Internal id generated per prediction service request
object PredictionRequestIdFeature extends Feature[TweetCandidate, Option[Long]]
object QuotedTweetIdFeature extends Feature[TweetCandidate, Option[Long]]
object QuotedUserIdFeature extends Feature[TweetCandidate, Option[Long]]
object ScoreFeature extends Feature[TweetCandidate, Option[Double]]
object SemanticCoreIdFeature extends Feature[TweetCandidate, Option[Long]]
// Key for kafka logging
object ServedIdFeature extends Feature[TweetCandidate, Option[Long]]
object SimclustersTweetTopKClustersWithScoresFeature
extends Feature[TweetCandidate, Map[String, Double]]
object SocialContextFeature extends Feature[TweetCandidate, Option[tst.SocialContext]]
object SourceTweetIdFeature
extends DataRecordOptionalFeature[TweetCandidate, Long]
with LongDiscreteDataRecordCompatible {
override val featureName: String = TimelinesSharedFeatures.SOURCE_TWEET_ID.getFeatureName
override val personalDataTypes: Set[pd.PersonalDataType] = Set(pd.PersonalDataType.TweetId)
}
object SourceUserIdFeature extends Feature[TweetCandidate, Option[Long]]
object StreamToKafkaFeature extends Feature[TweetCandidate, Boolean]
object SuggestTypeFeature extends Feature[TweetCandidate, Option[st.SuggestType]]
object TSPMetricTagFeature extends Feature[TweetCandidate, Set[tsp.MetricTag]]
object TweetLanguageFeature extends Feature[TweetCandidate, Option[String]]
object TweetUrlsFeature extends Feature[TweetCandidate, Seq[String]]
object VideoDurationMsFeature extends Feature[TweetCandidate, Option[Int]]
object ViewerIdFeature
extends DataRecordFeature[TweetCandidate, Long]
with LongDiscreteDataRecordCompatible {
override def featureName: String = SharedFeatures.USER_ID.getFeatureName
override def personalDataTypes: Set[pd.PersonalDataType] = Set(pd.PersonalDataType.UserId)
}
object WeightedModelScoreFeature extends Feature[TweetCandidate, Option[Double]]
object MentionUserIdFeature extends Feature[TweetCandidate, Seq[Long]]
object MentionScreenNameFeature extends Feature[TweetCandidate, Seq[String]]
object HasImageFeature extends Feature[TweetCandidate, Boolean]
object HasVideoFeature extends Feature[TweetCandidate, Boolean]
// Tweetypie VF Features
object IsHydratedFeature extends Feature[TweetCandidate, Boolean]
object IsNsfwFeature extends Feature[TweetCandidate, Boolean]
object QuotedTweetDroppedFeature extends Feature[TweetCandidate, Boolean]
// Raw Tweet Text from Tweetypie
object TweetTextFeature extends Feature[TweetCandidate, Option[String]]
object AuthorEnabledPreviewsFeature extends Feature[TweetCandidate, Boolean]
object IsTweetPreviewFeature extends Feature[TweetCandidate, Boolean]
// SGS Features
/**
* By convention, this is set to true for retweets of non-followed authors
* E.g. where somebody the viewer follows retweets a Tweet from somebody the viewer doesn't follow
*/
object InNetworkFeature extends FeatureWithDefaultOnFailure[TweetCandidate, Boolean] {
override val defaultValue: Boolean = true
}
// Query Features
object AccountAgeFeature extends Feature[PipelineQuery, Option[Time]]
object ClientIdFeature
extends DataRecordOptionalFeature[PipelineQuery, Long]
with LongDiscreteDataRecordCompatible {
override def featureName: String = SharedFeatures.CLIENT_ID.getFeatureName
override def personalDataTypes: Set[pd.PersonalDataType] = Set(pd.PersonalDataType.ClientType)
}
object CachedScoredTweetsFeature extends Feature[PipelineQuery, Seq[hmt.ScoredTweet]]
object DeviceLanguageFeature extends Feature[PipelineQuery, Option[String]]
object DismissInfoFeature
extends FeatureWithDefaultOnFailure[PipelineQuery, Map[st.SuggestType, Option[DismissInfo]]] {
override def defaultValue: Map[st.SuggestType, Option[DismissInfo]] = Map.empty
}
object FollowingLastNonPollingTimeFeature extends Feature[PipelineQuery, Option[Time]]
object GetInitialFeature
extends DataRecordFeature[PipelineQuery, Boolean]
with BoolDataRecordCompatible {
override def featureName: String = RequestContextFeatures.IS_GET_INITIAL.getFeatureName
override def personalDataTypes: Set[pd.PersonalDataType] = Set.empty
}
object GetMiddleFeature
extends DataRecordFeature[PipelineQuery, Boolean]
with BoolDataRecordCompatible {
override def featureName: String = RequestContextFeatures.IS_GET_MIDDLE.getFeatureName
override def personalDataTypes: Set[pd.PersonalDataType] = Set.empty
}
object GetNewerFeature
extends DataRecordFeature[PipelineQuery, Boolean]
with BoolDataRecordCompatible {
override def featureName: String = RequestContextFeatures.IS_GET_NEWER.getFeatureName
override def personalDataTypes: Set[pd.PersonalDataType] = Set.empty
}
object GetOlderFeature
extends DataRecordFeature[PipelineQuery, Boolean]
with BoolDataRecordCompatible {
override def featureName: String = RequestContextFeatures.IS_GET_OLDER.getFeatureName
override def personalDataTypes: Set[pd.PersonalDataType] = Set.empty
}
object GuestIdFeature
extends DataRecordOptionalFeature[PipelineQuery, Long]
with LongDiscreteDataRecordCompatible {
override def featureName: String = SharedFeatures.GUEST_ID.getFeatureName
override def personalDataTypes: Set[pd.PersonalDataType] = Set(pd.PersonalDataType.GuestId)
}
object HasDarkRequestFeature extends Feature[PipelineQuery, Option[Boolean]]
object ImpressionBloomFilterFeature
extends FeatureWithDefaultOnFailure[PipelineQuery, blm.ImpressionBloomFilterSeq] {
override def defaultValue: blm.ImpressionBloomFilterSeq =
blm.ImpressionBloomFilterSeq(Seq.empty)
}
object IsForegroundRequestFeature extends Feature[PipelineQuery, Boolean]
object IsLaunchRequestFeature extends Feature[PipelineQuery, Boolean]
object LastNonPollingTimeFeature extends Feature[PipelineQuery, Option[Time]]
object NonPollingTimesFeature extends Feature[PipelineQuery, Seq[Long]]
object PersistenceEntriesFeature extends Feature[PipelineQuery, Seq[TimelineResponseV3]]
object PollingFeature extends Feature[PipelineQuery, Boolean]
object PullToRefreshFeature extends Feature[PipelineQuery, Boolean]
// Scores from Real Graph representing the relationship between the viewer and another user
object RealGraphInNetworkScoresFeature extends Feature[PipelineQuery, Map[UserId, Double]]
object RequestJoinIdFeature extends Feature[TweetCandidate, Option[Long]]
// Internal id generated per request, mainly to deduplicate re-served cached tweets in logging
object ServedRequestIdFeature extends Feature[PipelineQuery, Option[Long]]
object ServedTweetIdsFeature extends Feature[PipelineQuery, Seq[Long]]
object ServedTweetPreviewIdsFeature extends Feature[PipelineQuery, Seq[Long]]
object TimelineServiceTweetsFeature extends Feature[PipelineQuery, Seq[Long]]
object TimestampFeature
extends DataRecordFeature[PipelineQuery, Long]
with LongDiscreteDataRecordCompatible {
override def featureName: String = SharedFeatures.TIMESTAMP.getFeatureName
override def personalDataTypes: Set[pd.PersonalDataType] = Set.empty
}
object TimestampGMTDowFeature
extends DataRecordFeature[PipelineQuery, Long]
with LongDiscreteDataRecordCompatible {
override def featureName: String = RequestContextFeatures.TIMESTAMP_GMT_DOW.getFeatureName
override def personalDataTypes: Set[pd.PersonalDataType] = Set.empty
}
object TimestampGMTHourFeature
extends DataRecordFeature[PipelineQuery, Long]
with LongDiscreteDataRecordCompatible {
override def featureName: String = RequestContextFeatures.TIMESTAMP_GMT_HOUR.getFeatureName
override def personalDataTypes: Set[pd.PersonalDataType] = Set.empty
}
object TweetImpressionsFeature extends Feature[PipelineQuery, Seq[imp.TweetImpressionsEntry]]
object UserFollowedTopicsCountFeature extends Feature[PipelineQuery, Option[Int]]
object UserFollowingCountFeature extends Feature[PipelineQuery, Option[Int]]
object UserScreenNameFeature extends Feature[PipelineQuery, Option[String]]
object UserStateFeature extends Feature[PipelineQuery, Option[um.UserState]]
object UserTypeFeature extends Feature[PipelineQuery, Option[gt.UserType]]
object WhoToFollowExcludedUserIdsFeature
extends FeatureWithDefaultOnFailure[PipelineQuery, Seq[Long]] {
override def defaultValue = Seq.empty
}
// Result Features
object ServedSizeFeature extends Feature[PipelineQuery, Option[Int]]
object HasRandomTweetFeature extends Feature[PipelineQuery, Boolean]
object IsRandomTweetAboveFeature extends Feature[TweetCandidate, Boolean]
object ServedInConversationModuleFeature extends Feature[TweetCandidate, Boolean]
object ConversationModule2DisplayedTweetsFeature extends Feature[TweetCandidate, Boolean]
object ConversationModuleHasGapFeature extends Feature[TweetCandidate, Boolean]
object SGSValidLikedByUserIdsFeature extends Feature[TweetCandidate, Seq[Long]]
object SGSValidFollowedByUserIdsFeature extends Feature[TweetCandidate, Seq[Long]]
object PerspectiveFilteredLikedByUserIdsFeature extends Feature[TweetCandidate, Seq[Long]]
object ScreenNamesFeature extends Feature[TweetCandidate, Map[Long, String]]
object RealNamesFeature extends Feature[TweetCandidate, Map[Long, String]]
/**
* Features around the focal Tweet for Tweets which should be rendered in convo modules.
* These are needed in order to render social context above the root tweet in a convo modules.
* For example if we have a convo module A-B-C (A Tweets, B replies to A, C replies to B), the descendant features are
* for the Tweet C. These features are None except for the root Tweet for Tweets which should render into
* convo modules.
*/
object FocalTweetAuthorIdFeature extends Feature[TweetCandidate, Option[Long]]
object FocalTweetInNetworkFeature extends Feature[TweetCandidate, Option[Boolean]]
object FocalTweetRealNamesFeature extends Feature[TweetCandidate, Option[Map[Long, String]]]
object FocalTweetScreenNamesFeature extends Feature[TweetCandidate, Option[Map[Long, String]]]
object MediaUnderstandingAnnotationIdsFeature extends Feature[TweetCandidate, Seq[Long]]
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"dspbidder/thrift/src/main/thrift/com/twitter/dspbidder/commons:thrift-scala",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/common",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/marshalling/request",
"timelineservice/common:model",
],
exports = [
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/marshalling/request",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request/DeviceContext.scala | package com.twitter.home_mixer.model.request
import com.twitter.product_mixer.core.model.marshalling.request.ClientContext
import com.twitter.{timelineservice => tls}
case class DeviceContext(
isPolling: Option[Boolean],
requestContext: Option[String],
latestControlAvailable: Option[Boolean],
autoplayEnabled: Option[Boolean]) {
lazy val requestContextValue: Option[DeviceContext.RequestContext.Value] =
requestContext.flatMap { value =>
val normalizedValue = value.trim.toLowerCase()
DeviceContext.RequestContext.values.find(_.toString == normalizedValue)
}
def toTimelineServiceDeviceContext(clientContext: ClientContext): tls.DeviceContext =
tls.DeviceContext(
countryCode = clientContext.countryCode,
languageCode = clientContext.languageCode,
clientAppId = clientContext.appId,
ipAddress = clientContext.ipAddress,
guestId = clientContext.guestId,
sessionId = None,
timezone = None,
userAgent = clientContext.userAgent,
deviceId = clientContext.deviceId,
isPolling = isPolling,
requestProvenance = requestContext,
referrer = None,
tfeAuthHeader = None,
mobileDeviceId = clientContext.mobileDeviceId,
isSessionStart = None,
displaySize = None,
isURTRequest = Some(true),
latestControlAvailable = latestControlAvailable,
guestIdMarketing = clientContext.guestIdMarketing,
isInternalOrTwoffice = clientContext.isTwoffice,
browserNotificationPermission = None,
guestIdAds = clientContext.guestIdAds,
)
}
object DeviceContext {
val Empty: DeviceContext = DeviceContext(
isPolling = None,
requestContext = None,
latestControlAvailable = None,
autoplayEnabled = None
)
/**
* Constants which reflect valid client request provenances (why a request was initiated, encoded
* by the "request_context" HTTP parameter).
*/
object RequestContext extends Enumeration {
val Auto = Value("auto")
val Foreground = Value("foreground")
val Gap = Value("gap")
val Launch = Value("launch")
val ManualRefresh = Value("manual_refresh")
val Navigate = Value("navigate")
val Polling = Value("polling")
val PullToRefresh = Value("ptr")
val Signup = Value("signup")
val TweetSelfThread = Value("tweet_self_thread")
val BackgroundFetch = Value("background_fetch")
}
}
trait HasDeviceContext {
def deviceContext: Option[DeviceContext]
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request/HasListId.scala | package com.twitter.home_mixer.model.request
/**
* [[HasListId]] enables shared components to access the list id shared by all list timeline products.
*/
trait HasListId {
def listId: Long
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request/HasSeenTweetIds.scala | package com.twitter.home_mixer.model.request
/**
* [[HasSeenTweetIds]] enables shared components to access the list of impressed tweet IDs
* sent by clients across different Home Mixer query types (e.g. FollowingQuery, ForYouQuery)
*/
trait HasSeenTweetIds {
def seenTweetIds: Option[Seq[Long]]
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request/HomeMixerDebugOptions.scala | package com.twitter.home_mixer.model.request
import com.twitter.product_mixer.core.model.marshalling.request.DebugOptions
import com.twitter.util.Time
case class HomeMixerDebugOptions(
override val requestTimeOverride: Option[Time])
extends DebugOptions
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request/HomeMixerProduct.scala | package com.twitter.home_mixer.model.request
import com.twitter.product_mixer.core.model.common.identifier.ProductIdentifier
import com.twitter.product_mixer.core.model.marshalling.request.Product
/**
* Identifier names on products can be used to create Feature Switch rules by product,
* which useful if bucketing occurs in a component shared by multiple products.
* @see [[Product.identifier]]
*/
case object FollowingProduct extends Product {
override val identifier: ProductIdentifier = ProductIdentifier("Following")
override val stringCenterProject: Option[String] = Some("timelinemixer")
}
case object ForYouProduct extends Product {
override val identifier: ProductIdentifier = ProductIdentifier("ForYou")
override val stringCenterProject: Option[String] = Some("timelinemixer")
}
case object ScoredTweetsProduct extends Product {
override val identifier: ProductIdentifier = ProductIdentifier("ScoredTweets")
override val stringCenterProject: Option[String] = Some("timelinemixer")
}
case object ListTweetsProduct extends Product {
override val identifier: ProductIdentifier = ProductIdentifier("ListTweets")
override val stringCenterProject: Option[String] = Some("timelinemixer")
}
case object ListRecommendedUsersProduct extends Product {
override val identifier: ProductIdentifier = ProductIdentifier("ListRecommendedUsers")
override val stringCenterProject: Option[String] = Some("timelinemixer")
}
case object SubscribedProduct extends Product {
override val identifier: ProductIdentifier = ProductIdentifier("Subscribed")
override val stringCenterProject: Option[String] = Some("timelinemixer")
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request/HomeMixerProductContext.scala | package com.twitter.home_mixer.model.request
import com.twitter.dspbidder.commons.thriftscala.DspClientContext
import com.twitter.product_mixer.core.model.marshalling.request.ProductContext
case class FollowingProductContext(
deviceContext: Option[DeviceContext],
seenTweetIds: Option[Seq[Long]],
dspClientContext: Option[DspClientContext])
extends ProductContext
case class ForYouProductContext(
deviceContext: Option[DeviceContext],
seenTweetIds: Option[Seq[Long]],
dspClientContext: Option[DspClientContext],
pushToHomeTweetId: Option[Long])
extends ProductContext
case class ScoredTweetsProductContext(
deviceContext: Option[DeviceContext],
seenTweetIds: Option[Seq[Long]],
servedTweetIds: Option[Seq[Long]],
backfillTweetIds: Option[Seq[Long]])
extends ProductContext
case class ListTweetsProductContext(
listId: Long,
deviceContext: Option[DeviceContext],
dspClientContext: Option[DspClientContext])
extends ProductContext
case class ListRecommendedUsersProductContext(
listId: Long,
selectedUserIds: Option[Seq[Long]],
excludedUserIds: Option[Seq[Long]],
listName: Option[String])
extends ProductContext
case class SubscribedProductContext(
deviceContext: Option[DeviceContext],
seenTweetIds: Option[Seq[Long]])
extends ProductContext
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/model/request/HomeMixerRequest.scala | package com.twitter.home_mixer.model.request
import com.twitter.product_mixer.core.model.marshalling.request.ClientContext
import com.twitter.product_mixer.core.model.marshalling.request.DebugParams
import com.twitter.product_mixer.core.model.marshalling.request.Product
import com.twitter.product_mixer.core.model.marshalling.request.ProductContext
import com.twitter.product_mixer.core.model.marshalling.request.Request
case class HomeMixerRequest(
override val clientContext: ClientContext,
override val product: Product,
// Product-specific parameters should be placed in the Product Context
override val productContext: Option[ProductContext],
override val serializedRequestCursor: Option[String],
override val maxResults: Option[Int],
override val debugParams: Option[DebugParams],
// Parameters that apply to all products can be promoted to the request-level
homeRequestParam: Boolean)
extends Request
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/AdvertiserBrandSafetySettingsStoreModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.adserver.{thriftscala => ads}
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.inject.TwitterModule
import com.twitter.storage.client.manhattan.kv.Guarantee
import com.twitter.storehaus.ReadableStore
import com.twitter.storehaus_internal.manhattan.ManhattanCluster
import com.twitter.storehaus_internal.manhattan.ManhattanClusters
import com.twitter.timelines.clients.ads.AdvertiserBrandSafetySettingsStore
import com.twitter.timelines.clients.manhattan.mhv3.ManhattanClientBuilder
import com.twitter.timelines.clients.manhattan.mhv3.ManhattanClientConfigWithDataset
import com.twitter.util.Duration
import javax.inject.Singleton
object AdvertiserBrandSafetySettingsStoreModule extends TwitterModule {
@Provides
@Singleton
def providesAdvertiserBrandSafetySettingsStore(
injectedServiceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): ReadableStore[Long, ads.AdvertiserBrandSafetySettings] = {
val advertiserBrandSafetySettingsManhattanClientConfig = new ManhattanClientConfigWithDataset {
override val cluster: ManhattanCluster = ManhattanClusters.apollo
override val appId: String = "brand_safety_apollo"
override val dataset = "advertiser_brand_safety_settings"
override val statsScope: String = "AdvertiserBrandSafetySettingsManhattanClient"
override val defaultGuarantee = Guarantee.Weak
override val defaultMaxTimeout: Duration = 100.milliseconds
override val maxRetryCount: Int = 1
override val isReadOnly: Boolean = true
override val serviceIdentifier: ServiceIdentifier = injectedServiceIdentifier
}
val advertiserBrandSafetySettingsManhattanEndpoint = ManhattanClientBuilder
.buildManhattanEndpoint(advertiserBrandSafetySettingsManhattanClientConfig, statsReceiver)
val advertiserBrandSafetySettingsStore: ReadableStore[Long, ads.AdvertiserBrandSafetySettings] =
AdvertiserBrandSafetySettingsStore
.cached(
advertiserBrandSafetySettingsManhattanEndpoint,
advertiserBrandSafetySettingsManhattanClientConfig.dataset,
ttl = 60.minutes,
maxKeys = 100000,
windowSize = 10L
)(statsReceiver)
advertiserBrandSafetySettingsStore
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"3rdparty/jvm/com/twitter/bijection:scrooge",
"3rdparty/jvm/com/twitter/bijection:thrift",
"3rdparty/jvm/com/twitter/src/java/com/twitter/logpipeline/client:logpipeline-event-publisher-thin",
"3rdparty/jvm/com/twitter/storehaus:core",
"3rdparty/jvm/io/netty:netty4-tcnative-boringssl-static",
"eventbus/client/src/main/scala/com/twitter/eventbus/client",
"finagle-internal/finagle-grpc/src/main/scala",
"finagle-internal/mtls/src/main/scala/com/twitter/finagle/mtls/authentication",
"finagle-internal/mtls/src/main/scala/com/twitter/finagle/mtls/client",
"finagle/finagle-core/src/main",
"finagle/finagle-memcached/src/main/scala",
"finagle/finagle-mux/src/main/scala",
"finagle/finagle-thriftmux/src/main/scala",
"finatra/inject/inject-core/src/main/scala",
"hermit/hermit-core/src/main/scala/com/twitter/hermit/store/common",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/functional_component/feature_hydrator",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/param",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/store",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/util",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/util/earlybird",
"home-mixer/server/src/main/scala/com/twitter/home_mixer/util/tweetypie",
"home-mixer/thrift/src/main/thrift:thrift-scala",
"interests-service/thrift/src/main/thrift:thrift-scala",
"people-discovery/api/thrift/src/main/thrift:thrift-scala",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/module",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/pipeline",
"product-mixer/shared-library/src/main/scala/com/twitter/product_mixer/shared_library/manhattan_client",
"product-mixer/shared-library/src/main/scala/com/twitter/product_mixer/shared_library/memcached_client",
"product-mixer/shared-library/src/main/scala/com/twitter/product_mixer/shared_library/thrift_client",
"servo/client/src/main/scala/com/twitter/servo/client",
"servo/manhattan",
"servo/util",
"socialgraph/server/src/main/scala/com/twitter/socialgraph/util",
"src/scala/com/twitter/ml/featurestore/lib",
"src/scala/com/twitter/scalding_internal/multiformat/format",
"src/scala/com/twitter/storehaus_internal",
"src/scala/com/twitter/summingbird_internal/bijection:bijection-implicits",
"src/scala/com/twitter/timelines/util",
"src/thrift/com/twitter/ads/adserver:adserver_rpc-scala",
"src/thrift/com/twitter/clientapp/gen:clientapp-scala",
"src/thrift/com/twitter/hermit/candidate:hermit-candidate-scala",
"src/thrift/com/twitter/manhattan:v1-scala",
"src/thrift/com/twitter/manhattan:v2-scala",
"src/thrift/com/twitter/onboarding/relevance/features:features-java",
"src/thrift/com/twitter/search:blender-scala",
"src/thrift/com/twitter/search:earlybird-scala",
"src/thrift/com/twitter/service/metastore/gen:thrift-scala",
"src/thrift/com/twitter/socialgraph:thrift-scala",
"src/thrift/com/twitter/timelines/author_features:thrift-java",
"src/thrift/com/twitter/timelines/impression_bloom_filter:thrift-scala",
"src/thrift/com/twitter/timelines/impression_store:thrift-scala",
"src/thrift/com/twitter/timelines/real_graph:real_graph-scala",
"src/thrift/com/twitter/timelines/suggests/common:poly_data_record-java",
"src/thrift/com/twitter/timelines/timeline_logging:thrift-scala",
"src/thrift/com/twitter/timelinescorer/common/scoredtweetcandidate:thrift-scala",
"src/thrift/com/twitter/topic_recos:topic_recos-thrift-java",
"src/thrift/com/twitter/user_session_store:thrift-java",
"src/thrift/com/twitter/wtf/candidate:wtf-candidate-scala",
"stitch/stitch-socialgraph",
"stitch/stitch-tweetypie",
"strato/src/main/scala/com/twitter/strato/client",
"timelinemixer/common/src/main/scala/com/twitter/timelinemixer/clients/feedback",
"timelinemixer/common/src/main/scala/com/twitter/timelinemixer/clients/manhattan",
"timelinemixer/server/src/main/scala/com/twitter/timelinemixer/injection/store/persistence",
"timelines:decider",
"timelines/src/main/scala/com/twitter/timelines/clients/ads",
"timelines/src/main/scala/com/twitter/timelines/clients/manhattan",
"timelines/src/main/scala/com/twitter/timelines/clients/manhattan/store",
"timelines/src/main/scala/com/twitter/timelines/clients/predictionservice",
"timelines/src/main/scala/com/twitter/timelines/clients/strato",
"timelines/src/main/scala/com/twitter/timelines/clients/strato/topics",
"timelines/src/main/scala/com/twitter/timelines/clients/strato/twistly",
"timelines/src/main/scala/com/twitter/timelines/config",
"timelines/src/main/scala/com/twitter/timelines/impressionstore/impressionbloomfilter",
"timelines/src/main/scala/com/twitter/timelines/impressionstore/store",
"timelines/src/main/scala/com/twitter/timelines/util/stats",
"timelineservice/common/src/main/scala/com/twitter/timelineservice/model",
"tweetconvosvc/client/src/main/scala/com/twitter/tweetconvosvc/client/builder",
"twitter-config/yaml",
],
exports = [
"timelines/src/main/scala/com/twitter/timelines/clients/predictionservice",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/BlenderClientModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.finagle.thrift.ClientId
import com.twitter.inject.TwitterModule
import com.twitter.product_mixer.shared_library.thrift_client.FinagleThriftClientBuilder
import com.twitter.product_mixer.shared_library.thrift_client.NonIdempotent
import com.twitter.search.blender.thriftscala.BlenderService
import javax.inject.Singleton
object BlenderClientModule extends TwitterModule {
@Singleton
@Provides
def providesBlenderClient(
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): BlenderService.MethodPerEndpoint = {
val clientId = serviceIdentifier.environment.toLowerCase match {
case "prod" => ClientId("")
case _ => ClientId("")
}
FinagleThriftClientBuilder.buildFinagleMethodPerEndpoint[
BlenderService.ServicePerEndpoint,
BlenderService.MethodPerEndpoint
](
serviceIdentifier = serviceIdentifier,
clientId = clientId,
dest = "/s/blender-universal/blender",
label = "blender",
statsReceiver = statsReceiver,
idempotency = NonIdempotent,
timeoutPerRequest = 1000.milliseconds,
timeoutTotal = 1000.milliseconds,
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/ClientSentImpressionsPublisherModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.eventbus.client.EventBusPublisher
import com.twitter.eventbus.client.EventBusPublisherBuilder
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.inject.TwitterModule
import com.twitter.timelines.config.ConfigUtils
import com.twitter.timelines.config.Env
import com.twitter.timelines.impressionstore.thriftscala.PublishedImpressionList
import javax.inject.Singleton
object ClientSentImpressionsPublisherModule extends TwitterModule with ConfigUtils {
private val serviceName = "home-mixer"
@Singleton
@Provides
def providesClientSentImpressionsPublisher(
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): EventBusPublisher[PublishedImpressionList] = {
val env = serviceIdentifier.environment.toLowerCase match {
case "prod" => Env.prod
case "staging" => Env.staging
case "local" => Env.local
case _ => Env.devel
}
val streamName = env match {
case Env.prod => "timelinemixer_client_sent_impressions_prod"
case _ => "timelinemixer_client_sent_impressions_devel"
}
EventBusPublisherBuilder()
.clientId(clientIdWithScopeOpt(serviceName, env))
.serviceIdentifier(serviceIdentifier)
.streamName(streamName)
.statsReceiver(statsReceiver.scope("eventbus"))
.thriftStruct(PublishedImpressionList)
.tcpConnectTimeout(20.milliseconds)
.connectTimeout(100.milliseconds)
.requestTimeout(1.second)
.publishTimeout(1.second)
.build()
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/ConversationServiceModule.scala | package com.twitter.home_mixer.module
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.ThriftMux
import com.twitter.finagle.thriftmux.MethodBuilder
import com.twitter.finatra.mtls.thriftmux.modules.MtlsClient
import com.twitter.inject.Injector
import com.twitter.inject.thrift.modules.ThriftMethodBuilderClientModule
import com.twitter.tweetconvosvc.thriftscala.ConversationService
import com.twitter.util.Duration
import org.apache.thrift.protocol.TCompactProtocol
object ConversationServiceModule
extends ThriftMethodBuilderClientModule[
ConversationService.ServicePerEndpoint,
ConversationService.MethodPerEndpoint
]
with MtlsClient {
override val label: String = "tweetconvosvc"
override val dest: String = "/s/tweetconvosvc/tweetconvosvc"
override protected def configureMethodBuilder(
injector: Injector,
methodBuilder: MethodBuilder
): MethodBuilder = methodBuilder.withTimeoutPerRequest(100.milliseconds)
override def configureThriftMuxClient(
injector: Injector,
client: ThriftMux.Client
): ThriftMux.Client =
super
.configureThriftMuxClient(injector, client)
.withProtocolFactory(new TCompactProtocol.Factory())
override protected def sessionAcquisitionTimeout: Duration = 500.milliseconds
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/FeedbackHistoryClientModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.inject.TwitterModule
import com.twitter.inject.annotations.Flag
import com.twitter.timelinemixer.clients.feedback.FeedbackHistoryManhattanClient
import com.twitter.timelinemixer.clients.feedback.FeedbackHistoryManhattanClientConfig
import com.twitter.timelines.clients.manhattan.mhv3.ManhattanClientBuilder
import com.twitter.util.Duration
import javax.inject.Singleton
object FeedbackHistoryClientModule extends TwitterModule {
private val ProdDataset = "feedback_history"
private val StagingDataset = "feedback_history_nonprod"
private final val Timeout = "mh_feedback_history.timeout"
flag[Duration](Timeout, 150.millis, "Timeout per request")
@Provides
@Singleton
def providesFeedbackHistoryClient(
@Flag(Timeout) timeout: Duration,
serviceId: ServiceIdentifier,
statsReceiver: StatsReceiver
) = {
val manhattanDataset = serviceId.environment.toLowerCase match {
case "prod" => ProdDataset
case _ => StagingDataset
}
val config = new FeedbackHistoryManhattanClientConfig {
val dataset = manhattanDataset
val isReadOnly = true
val serviceIdentifier = serviceId
override val defaultMaxTimeout = timeout
}
new FeedbackHistoryManhattanClient(
ManhattanClientBuilder.buildManhattanEndpoint(config, statsReceiver),
manhattanDataset,
statsReceiver
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/HomeAdsCandidateSourceModule.scala | package com.twitter.home_mixer.module
import com.twitter.adserver.thriftscala.NewAdServer
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.thriftmux.MethodBuilder
import com.twitter.finatra.mtls.thriftmux.modules.MtlsClient
import com.twitter.inject.Injector
import com.twitter.inject.thrift.modules.ThriftMethodBuilderClientModule
import com.twitter.util.Duration
object HomeAdsCandidateSourceModule
extends ThriftMethodBuilderClientModule[
NewAdServer.ServicePerEndpoint,
NewAdServer.MethodPerEndpoint
]
with MtlsClient {
override val label = "adserver"
override val dest = "/s/ads/adserver"
override protected def configureMethodBuilder(
injector: Injector,
methodBuilder: MethodBuilder
): MethodBuilder = {
methodBuilder
.withTimeoutPerRequest(1200.milliseconds)
.withTimeoutTotal(1200.milliseconds)
.withMaxRetries(2)
}
override protected def sessionAcquisitionTimeout: Duration = 150.milliseconds
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/HomeMixerFlagsModule.scala | package com.twitter.home_mixer.module
import com.twitter.conversions.DurationOps.RichDuration
import com.twitter.home_mixer.param.HomeMixerFlagName
import com.twitter.inject.TwitterModule
import com.twitter.util.Duration
object HomeMixerFlagsModule extends TwitterModule {
import HomeMixerFlagName._
flag[Boolean](
name = ScribeClientEventsFlag,
default = false,
help = "Toggles logging client events to Scribe"
)
flag[Boolean](
name = ScribeServedCandidatesFlag,
default = false,
help = "Toggles logging served candidates to Scribe"
)
flag[Boolean](
name = ScribeScoredCandidatesFlag,
default = false,
help = "Toggles logging scored candidates to Scribe"
)
flag[Boolean](
name = ScribeServedCommonFeaturesAndCandidateFeaturesFlag,
default = false,
help = "Toggles logging served common features and candidates features to Scribe"
)
flag[String](
name = DataRecordMetadataStoreConfigsYmlFlag,
default = "",
help = "The YML file that contains the necessary info for creating metadata store MySQL client."
)
flag[String](
name = DarkTrafficFilterDeciderKey,
default = "dark_traffic_filter",
help = "Dark traffic filter decider key"
)
flag[Duration](
TargetFetchLatency,
300.millis,
"Target fetch latency from candidate sources for Quality Factor"
)
flag[Duration](
TargetScoringLatency,
700.millis,
"Target scoring latency for Quality Factor"
)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/HomeMixerResourcesModule.scala | package com.twitter.home_mixer.module
import com.twitter.inject.TwitterModule
object HomeMixerResourcesModule extends TwitterModule {}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/ImpressionBloomFilterModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.inject.TwitterModule
import com.twitter.inject.annotations.Flag
import com.twitter.storage.client.manhattan.kv.Guarantee
import com.twitter.storehaus_internal.manhattan.ManhattanClusters
import com.twitter.timelines.clients.manhattan.store._
import com.twitter.timelines.impressionbloomfilter.{thriftscala => blm}
import com.twitter.timelines.impressionstore.impressionbloomfilter.ImpressionBloomFilterManhattanKeyValueDescriptor
import com.twitter.util.Duration
import javax.inject.Singleton
object ImpressionBloomFilterModule extends TwitterModule {
private val ProdAppId = "impression_bloom_filter_store"
private val ProdDataset = "impression_bloom_filter"
private val StagingAppId = "impression_bloom_filter_store_staging"
private val StagingDataset = "impression_bloom_filter_staging"
private val ClientStatsScope = "tweetBloomFilterImpressionManhattanClient"
private val DefaultTTL = 7.days
private final val Timeout = "mh_impression_store_bloom_filter.timeout"
flag[Duration](Timeout, 150.millis, "Timeout per request")
@Provides
@Singleton
def providesImpressionBloomFilter(
@Flag(Timeout) timeout: Duration,
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): ManhattanStoreClient[blm.ImpressionBloomFilterKey, blm.ImpressionBloomFilterSeq] = {
val (appId, dataset) = serviceIdentifier.environment.toLowerCase match {
case "prod" => (ProdAppId, ProdDataset)
case _ => (StagingAppId, StagingDataset)
}
implicit val manhattanKeyValueDescriptor: ImpressionBloomFilterManhattanKeyValueDescriptor =
ImpressionBloomFilterManhattanKeyValueDescriptor(
dataset = dataset,
ttl = DefaultTTL
)
ManhattanStoreClientBuilder.buildManhattanClient(
serviceIdentifier = serviceIdentifier,
cluster = ManhattanClusters.nash,
appId = appId,
defaultMaxTimeout = timeout,
maxRetryCount = 2,
defaultGuarantee = Some(Guarantee.SoftDcReadMyWrites),
isReadOnly = false,
statsScope = ClientStatsScope,
statsReceiver = statsReceiver
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/InjectionHistoryClientModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.ThriftMux
import com.twitter.finagle.builder.ClientBuilder
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.mtls.client.MtlsStackClient._
import com.twitter.finagle.service.RetryPolicy
import com.twitter.finagle.ssl.OpportunisticTls
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.inject.TwitterModule
import com.twitter.manhattan.v2.thriftscala.{ManhattanCoordinator => ManhattanV2}
import com.twitter.timelinemixer.clients.manhattan.InjectionHistoryClient
import com.twitter.timelinemixer.clients.manhattan.ManhattanDatasetConfig
import com.twitter.timelines.clients.manhattan.Dataset
import com.twitter.timelines.clients.manhattan.ManhattanClient
import com.twitter.timelines.util.stats.RequestScope
import javax.inject.Singleton
import org.apache.thrift.protocol.TBinaryProtocol
import com.twitter.timelines.config.TimelinesUnderlyingClientConfiguration.ConnectTimeout
import com.twitter.timelines.config.TimelinesUnderlyingClientConfiguration.TCPConnectTimeout
object InjectionHistoryClientModule extends TwitterModule {
private val ProdDataset = "suggestion_history"
private val StagingDataset = "suggestion_history_nonprod"
private val AppId = "twitter_suggests"
private val ServiceName = "manhattan.omega"
private val OmegaManhattanDest = "/s/manhattan/omega.native-thrift"
private val InjectionRequestScope = RequestScope("injectionHistoryClient")
private val RequestTimeout = 75.millis
private val Timeout = 150.millis
val retryPolicy = RetryPolicy.tries(
2,
RetryPolicy.TimeoutAndWriteExceptionsOnly
.orElse(RetryPolicy.ChannelClosedExceptionsOnly))
@Provides
@Singleton
def providesInjectionHistoryClient(
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
) = {
val dataset = serviceIdentifier.environment.toLowerCase match {
case "prod" => ProdDataset
case _ => StagingDataset
}
val thriftMuxClient = ClientBuilder()
.name(ServiceName)
.daemon(daemonize = true)
.failFast(enabled = true)
.retryPolicy(retryPolicy)
.tcpConnectTimeout(TCPConnectTimeout)
.connectTimeout(ConnectTimeout)
.dest(OmegaManhattanDest)
.requestTimeout(RequestTimeout)
.timeout(Timeout)
.stack(ThriftMux.client
.withMutualTls(serviceIdentifier)
.withOpportunisticTls(OpportunisticTls.Required))
.build()
val manhattanOmegaClient = new ManhattanV2.FinagledClient(
service = thriftMuxClient,
protocolFactory = new TBinaryProtocol.Factory(),
serviceName = ServiceName,
)
val readOnlyMhClient = new ManhattanClient(
appId = AppId,
manhattan = manhattanOmegaClient,
requestScope = InjectionRequestScope,
serviceName = ServiceName,
statsReceiver = statsReceiver
).readOnly
val mhDatasetConfig = new ManhattanDatasetConfig {
override val SuggestionHistoryDataset = Dataset(dataset)
}
new InjectionHistoryClient(
readOnlyMhClient,
mhDatasetConfig
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/ManhattanClientsModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.home_mixer.param.HomeMixerInjectionNames.RealGraphManhattanEndpoint
import com.twitter.inject.TwitterModule
import com.twitter.inject.annotations.Flag
import com.twitter.storage.client.manhattan.kv._
import com.twitter.timelines.config.ConfigUtils
import com.twitter.util.Duration
import javax.inject.Named
import javax.inject.Singleton
object ManhattanClientsModule extends TwitterModule with ConfigUtils {
private val ApolloDest = "/s/manhattan/apollo.native-thrift"
private final val Timeout = "mh_real_graph.timeout"
flag[Duration](Timeout, 150.millis, "Timeout total")
@Provides
@Singleton
@Named(RealGraphManhattanEndpoint)
def providesRealGraphManhattanEndpoint(
@Flag(Timeout) timeout: Duration,
serviceIdentifier: ServiceIdentifier
): ManhattanKVEndpoint = {
lazy val client = ManhattanKVClient(
appId = "real_graph",
dest = ApolloDest,
mtlsParams = ManhattanKVClientMtlsParams(serviceIdentifier = serviceIdentifier),
label = "real-graph-data"
)
ManhattanKVEndpointBuilder(client)
.maxRetryCount(2)
.defaultMaxTimeout(timeout)
.build()
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/ManhattanFeatureRepositoryModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.bijection.Injection
import com.twitter.bijection.scrooge.BinaryScalaCodec
import com.twitter.bijection.scrooge.CompactScalaCodec
import com.twitter.bijection.thrift.ThriftCodec
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.home_mixer.param.HomeMixerInjectionNames._
import com.twitter.home_mixer.util.InjectionTransformerImplicits._
import com.twitter.home_mixer.util.LanguageUtil
import com.twitter.home_mixer.util.TensorFlowUtil
import com.twitter.inject.TwitterModule
import com.twitter.manhattan.v1.{thriftscala => mh}
import com.twitter.ml.api.{thriftscala => ml}
import com.twitter.ml.featurestore.lib.UserId
import com.twitter.ml.featurestore.{thriftscala => fs}
import com.twitter.onboarding.relevance.features.{thriftjava => rf}
import com.twitter.product_mixer.shared_library.manhattan_client.ManhattanClientBuilder
import com.twitter.scalding_internal.multiformat.format.keyval.KeyValInjection.ScalaBinaryThrift
import com.twitter.search.common.constants.{thriftscala => scc}
import com.twitter.service.metastore.gen.{thriftscala => smg}
import com.twitter.servo.cache._
import com.twitter.servo.manhattan.ManhattanKeyValueRepository
import com.twitter.servo.repository.CachingKeyValueRepository
import com.twitter.servo.repository.ChunkingStrategy
import com.twitter.servo.repository.KeyValueRepository
import com.twitter.servo.repository.Repository
import com.twitter.servo.repository.keysAsQuery
import com.twitter.servo.util.Transformer
import com.twitter.storage.client.manhattan.bijections.Bijections
import com.twitter.storehaus_internal.manhattan.ManhattanClusters
import com.twitter.timelines.author_features.v1.{thriftjava => af}
import com.twitter.timelines.suggests.common.dense_data_record.{thriftscala => ddr}
import com.twitter.user_session_store.{thriftscala => uss_scala}
import com.twitter.user_session_store.{thriftjava => uss}
import com.twitter.util.Duration
import com.twitter.util.Try
import java.nio.ByteBuffer
import javax.inject.Named
import javax.inject.Singleton
import org.apache.thrift.protocol.TCompactProtocol
import org.apache.thrift.transport.TMemoryInputTransport
import org.apache.thrift.transport.TTransport
object ManhattanFeatureRepositoryModule extends TwitterModule {
private val DEFAULT_RPC_CHUNK_SIZE = 50
private val ThriftEntityIdInjection = ScalaBinaryThrift(fs.EntityId)
private val FeatureStoreUserIdKeyTransformer = new Transformer[Long, ByteBuffer] {
override def to(userId: Long): Try[ByteBuffer] = {
Try(ByteBuffer.wrap(ThriftEntityIdInjection.apply(UserId(userId).toThrift)))
}
override def from(b: ByteBuffer): Try[Long] = ???
}
private val FloatTensorTransformer = new Transformer[ByteBuffer, ml.FloatTensor] {
override def to(input: ByteBuffer): Try[ml.FloatTensor] = {
val floatTensor = TensorFlowUtil.embeddingByteBufferToFloatTensor(input)
Try(floatTensor)
}
override def from(b: ml.FloatTensor): Try[ByteBuffer] = ???
}
private val LanguageTransformer = new Transformer[ByteBuffer, Seq[scc.ThriftLanguage]] {
override def to(input: ByteBuffer): Try[Seq[scc.ThriftLanguage]] = {
Try.fromScala(
Bijections
.BinaryScalaInjection(smg.UserLanguages)
.andThen(Bijections.byteBuffer2Buf.inverse)
.invert(input).map(LanguageUtil.computeLanguages(_)))
}
override def from(b: Seq[scc.ThriftLanguage]): Try[ByteBuffer] = ???
}
private val LongKeyTransformer = Injection
.connect[Long, Array[Byte]]
.toByteBufferTransformer()
// manhattan clients
@Provides
@Singleton
@Named(ManhattanApolloClient)
def providesManhattanApolloClient(
serviceIdentifier: ServiceIdentifier
): mh.ManhattanCoordinator.MethodPerEndpoint = {
ManhattanClientBuilder
.buildManhattanV1FinagleClient(
ManhattanClusters.apollo,
serviceIdentifier
)
}
@Provides
@Singleton
@Named(ManhattanAthenaClient)
def providesManhattanAthenaClient(
serviceIdentifier: ServiceIdentifier
): mh.ManhattanCoordinator.MethodPerEndpoint = {
ManhattanClientBuilder
.buildManhattanV1FinagleClient(
ManhattanClusters.athena,
serviceIdentifier
)
}
@Provides
@Singleton
@Named(ManhattanOmegaClient)
def providesManhattanOmegaClient(
serviceIdentifier: ServiceIdentifier
): mh.ManhattanCoordinator.MethodPerEndpoint = {
ManhattanClientBuilder
.buildManhattanV1FinagleClient(
ManhattanClusters.omega,
serviceIdentifier
)
}
@Provides
@Singleton
@Named(ManhattanStarbuckClient)
def providesManhattanStarbuckClient(
serviceIdentifier: ServiceIdentifier
): mh.ManhattanCoordinator.MethodPerEndpoint = {
ManhattanClientBuilder
.buildManhattanV1FinagleClient(
ManhattanClusters.starbuck,
serviceIdentifier
)
}
// non-cached manhattan repositories
@Provides
@Singleton
@Named(MetricCenterUserCountingFeatureRepository)
def providesMetricCenterUserCountingFeatureRepository(
@Named(ManhattanStarbuckClient) client: mh.ManhattanCoordinator.MethodPerEndpoint
): KeyValueRepository[Seq[Long], Long, rf.MCUserCountingFeatures] = {
val valueTransformer = ThriftCodec
.toBinary[rf.MCUserCountingFeatures]
.toByteBufferTransformer()
.flip
batchedManhattanKeyValueRepository[Long, rf.MCUserCountingFeatures](
client = client,
keyTransformer = LongKeyTransformer,
valueTransformer = valueTransformer,
appId = "wtf_ml",
dataset = "mc_user_counting_features_v0_starbuck",
timeoutInMillis = 100
)
}
/**
* A repository of the offline aggregate feature metadata necessary to decode
* DenseCompactDataRecords.
*
* This repository is expected to virtually always pick up the metadata form the local cache with
* nearly 0 latency.
*/
@Provides
@Singleton
@Named(TimelineAggregateMetadataRepository)
def providesTimelineAggregateMetadataRepository(
@Named(ManhattanAthenaClient) client: mh.ManhattanCoordinator.MethodPerEndpoint
): Repository[Int, Option[ddr.DenseFeatureMetadata]] = {
val keyTransformer = Injection
.connect[Int, Array[Byte]]
.toByteBufferTransformer()
val valueTransformer = new Transformer[ByteBuffer, ddr.DenseFeatureMetadata] {
private val compactProtocolFactory = new TCompactProtocol.Factory
def to(buffer: ByteBuffer): Try[ddr.DenseFeatureMetadata] = Try {
val transport = transportFromByteBuffer(buffer)
ddr.DenseFeatureMetadata.decode(compactProtocolFactory.getProtocol(transport))
}
// Encoding intentionally not implemented as it is never used
def from(metadata: ddr.DenseFeatureMetadata): Try[ByteBuffer] = ???
}
val inProcessCache: Cache[Int, Cached[ddr.DenseFeatureMetadata]] = InProcessLruCacheFactory(
ttl = Duration.fromMinutes(20),
lruSize = 30
).apply(serializer = Transformer(_ => ???, _ => ???)) // Serialization is not necessary here.
val keyValueRepository = new ManhattanKeyValueRepository(
client = client,
keyTransformer = keyTransformer,
valueTransformer = valueTransformer,
appId = "timelines_dense_aggregates_encoding_metadata", // Expected QPS is negligible.
dataset = "user_session_dense_feature_metadata",
timeoutInMillis = 100
)
KeyValueRepository
.singular(
new CachingKeyValueRepository[Seq[Int], Int, ddr.DenseFeatureMetadata](
keyValueRepository,
new NonLockingCache(inProcessCache),
keysAsQuery[Int]
)
)
}
@Provides
@Singleton
@Named(RealGraphFeatureRepository)
def providesRealGraphFeatureRepository(
@Named(ManhattanAthenaClient) client: mh.ManhattanCoordinator.MethodPerEndpoint
): Repository[Long, Option[uss_scala.UserSession]] = {
val valueTransformer = CompactScalaCodec(uss_scala.UserSession).toByteBufferTransformer().flip
KeyValueRepository.singular(
new ManhattanKeyValueRepository(
client = client,
keyTransformer = LongKeyTransformer,
valueTransformer = valueTransformer,
appId = "real_graph",
dataset = "split_real_graph_features",
timeoutInMillis = 100,
)
)
}
// cached manhattan repositories
@Provides
@Singleton
@Named(AuthorFeatureRepository)
def providesAuthorFeatureRepository(
@Named(ManhattanAthenaClient) client: mh.ManhattanCoordinator.MethodPerEndpoint,
@Named(HomeAuthorFeaturesCacheClient) cacheClient: Memcache
): KeyValueRepository[Seq[Long], Long, af.AuthorFeatures] = {
val valueInjection = ThriftCodec
.toCompact[af.AuthorFeatures]
val keyValueRepository = batchedManhattanKeyValueRepository(
client = client,
keyTransformer = LongKeyTransformer,
valueTransformer = valueInjection.toByteBufferTransformer().flip,
appId = "timelines_author_feature_store_athena",
dataset = "timelines_author_features",
timeoutInMillis = 100
)
val remoteCacheRepo = buildMemCachedRepository(
keyValueRepository = keyValueRepository,
cacheClient = cacheClient,
cachePrefix = "AuthorFeatureHydrator",
ttl = 12.hours,
valueInjection = valueInjection)
buildInProcessCachedRepository(
keyValueRepository = remoteCacheRepo,
ttl = 15.minutes,
size = 8000,
valueInjection = valueInjection
)
}
@Provides
@Singleton
@Named(TwhinAuthorFollowFeatureRepository)
def providesTwhinAuthorFollowFeatureRepository(
@Named(ManhattanApolloClient) client: mh.ManhattanCoordinator.MethodPerEndpoint,
@Named(TwhinAuthorFollowFeatureCacheClient) cacheClient: Memcache
): KeyValueRepository[Seq[Long], Long, ml.FloatTensor] = {
val keyValueRepository =
batchedManhattanKeyValueRepository(
client = client,
keyTransformer = FeatureStoreUserIdKeyTransformer,
valueTransformer = FloatTensorTransformer,
appId = "ml_features_apollo",
dataset = "twhin_author_follow_embedding_fsv1__v1_thrift__embedding",
timeoutInMillis = 100
)
val valueInjection: Injection[ml.FloatTensor, Array[Byte]] =
BinaryScalaCodec(ml.FloatTensor)
buildMemCachedRepository(
keyValueRepository = keyValueRepository,
cacheClient = cacheClient,
cachePrefix = "twhinAuthorFollows",
ttl = 24.hours,
valueInjection = valueInjection
)
}
@Provides
@Singleton
@Named(UserLanguagesRepository)
def providesUserLanguagesFeatureRepository(
@Named(ManhattanStarbuckClient) client: mh.ManhattanCoordinator.MethodPerEndpoint
): KeyValueRepository[Seq[Long], Long, Seq[scc.ThriftLanguage]] = {
batchedManhattanKeyValueRepository(
client = client,
keyTransformer = LongKeyTransformer,
valueTransformer = LanguageTransformer,
appId = "user_metadata",
dataset = "languages",
timeoutInMillis = 70
)
}
@Provides
@Singleton
@Named(TwhinUserFollowFeatureRepository)
def providesTwhinUserFollowFeatureRepository(
@Named(ManhattanApolloClient) client: mh.ManhattanCoordinator.MethodPerEndpoint
): KeyValueRepository[Seq[Long], Long, ml.FloatTensor] = {
batchedManhattanKeyValueRepository(
client = client,
keyTransformer = FeatureStoreUserIdKeyTransformer,
valueTransformer = FloatTensorTransformer,
appId = "ml_features_apollo",
dataset = "twhin_user_follow_embedding_fsv1__v1_thrift__embedding",
timeoutInMillis = 100
)
}
@Provides
@Singleton
@Named(TimelineAggregatePartARepository)
def providesTimelineAggregatePartARepository(
@Named(ManhattanApolloClient) client: mh.ManhattanCoordinator.MethodPerEndpoint,
): Repository[Long, Option[uss.UserSession]] =
timelineAggregateRepository(
mhClient = client,
mhDataset = "timelines_aggregates_v2_features_by_user_part_a_apollo",
mhAppId = "timelines_aggregates_v2_features_by_user_part_a_apollo"
)
@Provides
@Singleton
@Named(TimelineAggregatePartBRepository)
def providesTimelineAggregatePartBRepository(
@Named(ManhattanApolloClient) client: mh.ManhattanCoordinator.MethodPerEndpoint,
): Repository[Long, Option[uss.UserSession]] =
timelineAggregateRepository(
mhClient = client,
mhDataset = "timelines_aggregates_v2_features_by_user_part_b_apollo",
mhAppId = "timelines_aggregates_v2_features_by_user_part_b_apollo"
)
@Provides
@Singleton
@Named(TwhinUserEngagementFeatureRepository)
def providesTwhinUserEngagementFeatureRepository(
@Named(ManhattanApolloClient) client: mh.ManhattanCoordinator.MethodPerEndpoint
): KeyValueRepository[Seq[Long], Long, ml.FloatTensor] = {
batchedManhattanKeyValueRepository(
client = client,
keyTransformer = FeatureStoreUserIdKeyTransformer,
valueTransformer = FloatTensorTransformer,
appId = "ml_features_apollo",
dataset = "twhin_user_engagement_embedding_fsv1__v1_thrift__embedding",
timeoutInMillis = 100
)
}
private def buildMemCachedRepository[K, V](
keyValueRepository: KeyValueRepository[Seq[K], K, V],
cacheClient: Memcache,
cachePrefix: String,
ttl: Duration,
valueInjection: Injection[V, Array[Byte]]
): CachingKeyValueRepository[Seq[K], K, V] = {
val cachedSerializer = CachedSerializer.binary(
valueInjection.toByteArrayTransformer()
)
val cache = MemcacheCacheFactory(
cacheClient,
ttl,
PrefixKeyTransformerFactory(cachePrefix)
)[K, Cached[V]](cachedSerializer)
new CachingKeyValueRepository(
keyValueRepository,
new NonLockingCache(cache),
keysAsQuery[K]
)
}
private def buildInProcessCachedRepository[K, V](
keyValueRepository: KeyValueRepository[Seq[K], K, V],
ttl: Duration,
size: Int,
valueInjection: Injection[V, Array[Byte]]
): CachingKeyValueRepository[Seq[K], K, V] = {
val cachedSerializer = CachedSerializer.binary(
valueInjection.toByteArrayTransformer()
)
val cache = InProcessLruCacheFactory(
ttl = ttl,
lruSize = size
)[K, Cached[V]](cachedSerializer)
new CachingKeyValueRepository(
keyValueRepository,
new NonLockingCache(cache),
keysAsQuery[K]
)
}
private def batchedManhattanKeyValueRepository[K, V](
client: mh.ManhattanCoordinator.MethodPerEndpoint,
keyTransformer: Transformer[K, ByteBuffer],
valueTransformer: Transformer[ByteBuffer, V],
appId: String,
dataset: String,
timeoutInMillis: Int,
chunkSize: Int = DEFAULT_RPC_CHUNK_SIZE
): KeyValueRepository[Seq[K], K, V] =
KeyValueRepository.chunked(
new ManhattanKeyValueRepository(
client = client,
keyTransformer = keyTransformer,
valueTransformer = valueTransformer,
appId = appId,
dataset = dataset,
timeoutInMillis = timeoutInMillis
),
chunker = ChunkingStrategy.equalSize(chunkSize)
)
private def transportFromByteBuffer(buffer: ByteBuffer): TTransport =
new TMemoryInputTransport(
buffer.array(),
buffer.arrayOffset() + buffer.position(),
buffer.remaining())
private def timelineAggregateRepository(
mhClient: mh.ManhattanCoordinator.MethodPerEndpoint,
mhDataset: String,
mhAppId: String
): Repository[Long, Option[uss.UserSession]] = {
val valueInjection = ThriftCodec
.toCompact[uss.UserSession]
KeyValueRepository.singular(
new ManhattanKeyValueRepository(
client = mhClient,
keyTransformer = LongKeyTransformer,
valueTransformer = valueInjection.toByteBufferTransformer().flip,
appId = mhAppId,
dataset = mhDataset,
timeoutInMillis = 100
)
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/ManhattanTweetImpressionStoreModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.inject.TwitterModule
import com.twitter.inject.annotations.Flag
import com.twitter.storage.client.manhattan.kv.Guarantee
import com.twitter.storehaus_internal.manhattan.ManhattanClusters
import com.twitter.timelines.clients.manhattan.mhv3.ManhattanClientBuilder
import com.twitter.timelines.impressionstore.store.ManhattanTweetImpressionStoreClientConfig
import com.twitter.timelines.impressionstore.store.ManhattanTweetImpressionStoreClient
import com.twitter.util.Duration
import javax.inject.Singleton
object ManhattanTweetImpressionStoreModule extends TwitterModule {
private val ProdAppId = "timelines_tweet_impression_store_v2"
private val ProdDataset = "timelines_tweet_impressions_v2"
private val StagingAppId = "timelines_tweet_impression_store_staging"
private val StagingDataset = "timelines_tweet_impressions_staging"
private val StatsScope = "manhattanTweetImpressionStoreClient"
private val DefaultTTL = 2.days
private final val Timeout = "mh_impression_store.timeout"
flag[Duration](Timeout, 150.millis, "Timeout per request")
@Provides
@Singleton
def providesManhattanTweetImpressionStoreClient(
@Flag(Timeout) timeout: Duration,
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): ManhattanTweetImpressionStoreClient = {
val (appId, dataset) = serviceIdentifier.environment.toLowerCase match {
case "prod" => (ProdAppId, ProdDataset)
case _ => (StagingAppId, StagingDataset)
}
val config = ManhattanTweetImpressionStoreClientConfig(
cluster = ManhattanClusters.nash,
appId = appId,
dataset = dataset,
statsScope = StatsScope,
defaultGuarantee = Guarantee.SoftDcReadMyWrites,
defaultMaxTimeout = timeout,
maxRetryCount = 2,
isReadOnly = false,
serviceIdentifier = serviceIdentifier,
ttl = DefaultTTL
)
val manhattanEndpoint = ManhattanClientBuilder.buildManhattanEndpoint(config, statsReceiver)
ManhattanTweetImpressionStoreClient(config, manhattanEndpoint, statsReceiver)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/MemcachedFeatureRepositoryModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.Memcached
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.home_mixer.param.HomeMixerInjectionNames.HomeAuthorFeaturesCacheClient
import com.twitter.home_mixer.param.HomeMixerInjectionNames.RealTimeInteractionGraphUserVertexClient
import com.twitter.home_mixer.param.HomeMixerInjectionNames.TimelinesRealTimeAggregateClient
import com.twitter.home_mixer.param.HomeMixerInjectionNames.TwhinAuthorFollowFeatureCacheClient
import com.twitter.inject.TwitterModule
import com.twitter.product_mixer.shared_library.memcached_client.MemcachedClientBuilder
import com.twitter.servo.cache.FinagleMemcacheFactory
import com.twitter.servo.cache.Memcache
import javax.inject.Named
import javax.inject.Singleton
object MemcachedFeatureRepositoryModule extends TwitterModule {
// This must match the respective parameter on the write path. Note that servo sets a different
// hasher by default. See [[com.twitter.hashing.KeyHasher]] for the list of other available
// hashers.
private val memcacheKeyHasher = "ketama"
@Provides
@Singleton
@Named(TimelinesRealTimeAggregateClient)
def providesTimelinesRealTimeAggregateClient(
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): Memcache = {
val rawClient = MemcachedClientBuilder.buildRawMemcachedClient(
numTries = 3,
numConnections = 1,
requestTimeout = 100.milliseconds,
globalTimeout = 300.milliseconds,
connectTimeout = 200.milliseconds,
acquisitionTimeout = 200.milliseconds,
serviceIdentifier = serviceIdentifier,
statsReceiver = statsReceiver
)
buildMemcacheClient(rawClient, "/s/cache/timelines_real_time_aggregates:twemcaches")
}
@Provides
@Singleton
@Named(HomeAuthorFeaturesCacheClient)
def providesHomeAuthorFeaturesCacheClient(
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): Memcache = {
val cacheClient = MemcachedClientBuilder.buildRawMemcachedClient(
numTries = 2,
numConnections = 1,
requestTimeout = 150.milliseconds,
globalTimeout = 300.milliseconds,
connectTimeout = 200.milliseconds,
acquisitionTimeout = 200.milliseconds,
serviceIdentifier = serviceIdentifier,
statsReceiver = statsReceiver
)
buildMemcacheClient(cacheClient, "/s/cache/timelines_author_features:twemcaches")
}
@Provides
@Singleton
@Named(TwhinAuthorFollowFeatureCacheClient)
def providesTwhinAuthorFollowFeatureCacheClient(
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): Memcache = {
val cacheClient = MemcachedClientBuilder.buildRawMemcachedClient(
numTries = 2,
numConnections = 1,
requestTimeout = 150.milliseconds,
globalTimeout = 300.milliseconds,
connectTimeout = 200.milliseconds,
acquisitionTimeout = 200.milliseconds,
serviceIdentifier = serviceIdentifier,
statsReceiver = statsReceiver
)
buildMemcacheClient(cacheClient, "/s/cache/home_twhin_author_features:twemcaches")
}
@Provides
@Singleton
@Named(RealTimeInteractionGraphUserVertexClient)
def providesRealTimeInteractionGraphUserVertexClient(
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): Memcache = {
val cacheClient = MemcachedClientBuilder.buildRawMemcachedClient(
numTries = 2,
numConnections = 1,
requestTimeout = 150.milliseconds,
globalTimeout = 300.milliseconds,
connectTimeout = 200.milliseconds,
acquisitionTimeout = 200.milliseconds,
serviceIdentifier = serviceIdentifier,
statsReceiver = statsReceiver
)
buildMemcacheClient(cacheClient, "/s/cache/realtime_interactive_graph_prod_v2:twemcaches")
}
private def buildMemcacheClient(cacheClient: Memcached.Client, dest: String): Memcache =
FinagleMemcacheFactory(
client = cacheClient,
dest = dest,
hashName = memcacheKeyHasher
)()
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/NaviModelClientModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.Http
import com.twitter.finagle.grpc.FinagleChannelBuilder
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.mtls.client.MtlsStackClient.MtlsStackClientSyntax
import com.twitter.inject.TwitterModule
import com.twitter.timelines.clients.predictionservice.PredictionGRPCService
import com.twitter.util.Duration
import io.grpc.ManagedChannel
import javax.inject.Singleton
object NaviModelClientModule extends TwitterModule {
@Singleton
@Provides
def providesPredictionGRPCService(
serviceIdentifier: ServiceIdentifier,
): PredictionGRPCService = {
// Wily path to the ML Model service (e.g. /s/ml-serving/navi-explore-ranker).
val modelPath = "/s/ml-serving/navi_home_recap_onnx"
val MaxPredictionTimeoutMs: Duration = 500.millis
val ConnectTimeoutMs: Duration = 200.millis
val AcquisitionTimeoutMs: Duration = 500.millis
val MaxRetryAttempts: Int = 2
val client = Http.client
.withLabel(modelPath)
.withMutualTls(serviceIdentifier)
.withRequestTimeout(MaxPredictionTimeoutMs)
.withTransport.connectTimeout(ConnectTimeoutMs)
.withSession.acquisitionTimeout(AcquisitionTimeoutMs)
.withHttpStats
val channel: ManagedChannel = FinagleChannelBuilder
.forTarget(modelPath)
.overrideAuthority("rustserving")
.maxRetryAttempts(MaxRetryAttempts)
.enableRetryForStatus(io.grpc.Status.RESOURCE_EXHAUSTED)
.enableRetryForStatus(io.grpc.Status.UNKNOWN)
.enableUnsafeFullyBufferingMode()
.httpClient(client)
.build()
new PredictionGRPCService(channel)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/OptimizedStratoClientModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.service.Retries
import com.twitter.finagle.service.RetryPolicy
import com.twitter.finagle.ssl.OpportunisticTls
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.home_mixer.param.HomeMixerInjectionNames.BatchedStratoClientWithModerateTimeout
import com.twitter.inject.TwitterModule
import com.twitter.strato.client.Client
import com.twitter.strato.client.Strato
import com.twitter.util.Try
import javax.inject.Named
import javax.inject.Singleton
object OptimizedStratoClientModule extends TwitterModule {
private val ModerateStratoServerClientRequestTimeout = 500.millis
private val DefaultRetryPartialFunction: PartialFunction[Try[Nothing], Boolean] =
RetryPolicy.TimeoutAndWriteExceptionsOnly
.orElse(RetryPolicy.ChannelClosedExceptionsOnly)
protected def mkRetryPolicy(tries: Int): RetryPolicy[Try[Nothing]] =
RetryPolicy.tries(tries, DefaultRetryPartialFunction)
@Singleton
@Provides
@Named(BatchedStratoClientWithModerateTimeout)
def providesStratoClient(
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): Client = {
Strato.client
.withMutualTls(serviceIdentifier, opportunisticLevel = OpportunisticTls.Required)
.withSession.acquisitionTimeout(500.milliseconds)
.withRequestTimeout(ModerateStratoServerClientRequestTimeout)
.withPerRequestTimeout(ModerateStratoServerClientRequestTimeout)
.withRpcBatchSize(5)
.configured(Retries.Policy(mkRetryPolicy(1)))
.withStatsReceiver(statsReceiver.scope("strato_client"))
.build()
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/PeopleDiscoveryServiceModule.scala | package com.twitter.home_mixer.module
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.thriftmux.MethodBuilder
import com.twitter.finatra.mtls.thriftmux.modules.MtlsClient
import com.twitter.inject.Injector
import com.twitter.inject.thrift.modules.ThriftMethodBuilderClientModule
import com.twitter.peoplediscovery.api.thriftscala.ThriftPeopleDiscoveryService
import com.twitter.util.Duration
/**
* Copy of com.twitter.product_mixer.component_library.module.PeopleDiscoveryServiceModule
*/
object PeopleDiscoveryServiceModule
extends ThriftMethodBuilderClientModule[
ThriftPeopleDiscoveryService.ServicePerEndpoint,
ThriftPeopleDiscoveryService.MethodPerEndpoint
]
with MtlsClient {
override val label: String = "people-discovery-api"
override val dest: String = "/s/people-discovery-api/people-discovery-api:thrift"
override protected def configureMethodBuilder(
injector: Injector,
methodBuilder: MethodBuilder
): MethodBuilder = {
methodBuilder
.withTimeoutPerRequest(350.millis)
.withTimeoutTotal(350.millis)
}
override protected def sessionAcquisitionTimeout: Duration = 500.milliseconds
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/PipelineFailureExceptionMapper.scala | package com.twitter.home_mixer.module
import com.twitter.finatra.thrift.exceptions.ExceptionMapper
import com.twitter.home_mixer.{thriftscala => t}
import com.twitter.util.logging.Logging
import com.twitter.product_mixer.core.pipeline.pipeline_failure.PipelineFailure
import com.twitter.product_mixer.core.pipeline.pipeline_failure.ProductDisabled
import com.twitter.scrooge.ThriftException
import com.twitter.util.Future
import javax.inject.Singleton
@Singleton
class PipelineFailureExceptionMapper
extends ExceptionMapper[PipelineFailure, ThriftException]
with Logging {
def handleException(throwable: PipelineFailure): Future[ThriftException] = {
throwable match {
// SliceService (unlike UrtService) throws an exception when the requested product is disabled
case PipelineFailure(ProductDisabled, reason, _, _) =>
Future.exception(
t.ValidationExceptionList(errors =
Seq(t.ValidationException(t.ValidationErrorCode.ProductDisabled, reason))))
case _ =>
error("Unhandled PipelineFailure", throwable)
Future.exception(throwable)
}
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/RealGraphInNetworkScoresModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.google.inject.name.Named
import com.twitter.home_mixer.param.HomeMixerInjectionNames.RealGraphInNetworkScores
import com.twitter.home_mixer.param.HomeMixerInjectionNames.RealGraphManhattanEndpoint
import com.twitter.home_mixer.store.RealGraphInNetworkScoresStore
import com.twitter.inject.TwitterModule
import com.twitter.storage.client.manhattan.kv.ManhattanKVEndpoint
import com.twitter.storehaus.ReadableStore
import com.twitter.timelines.util.CommonTypes.ViewerId
import com.twitter.wtf.candidate.thriftscala.Candidate
import javax.inject.Singleton
object RealGraphInNetworkScoresModule extends TwitterModule {
@Provides
@Singleton
@Named(RealGraphInNetworkScores)
def providesRealGraphInNetworkScoresFeaturesStore(
@Named(RealGraphManhattanEndpoint) realGraphInNetworkScoresManhattanKVEndpoint: ManhattanKVEndpoint
): ReadableStore[ViewerId, Seq[Candidate]] = {
new RealGraphInNetworkScoresStore(realGraphInNetworkScoresManhattanKVEndpoint)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/RealtimeAggregateFeatureRepositoryModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.google.inject.name.Named
import com.twitter.bijection.Injection
import com.twitter.bijection.scrooge.BinaryScalaCodec
import com.twitter.bijection.thrift.ThriftCodec
import com.twitter.home_mixer.param.HomeMixerInjectionNames.EngagementsReceivedByAuthorCache
import com.twitter.home_mixer.param.HomeMixerInjectionNames.RealTimeInteractionGraphUserVertexCache
import com.twitter.home_mixer.param.HomeMixerInjectionNames.RealTimeInteractionGraphUserVertexClient
import com.twitter.home_mixer.param.HomeMixerInjectionNames.TimelinesRealTimeAggregateClient
import com.twitter.home_mixer.param.HomeMixerInjectionNames.TopicCountryEngagementCache
import com.twitter.home_mixer.param.HomeMixerInjectionNames.TopicEngagementCache
import com.twitter.home_mixer.param.HomeMixerInjectionNames.TweetCountryEngagementCache
import com.twitter.home_mixer.param.HomeMixerInjectionNames.TweetEngagementCache
import com.twitter.home_mixer.param.HomeMixerInjectionNames.TwitterListEngagementCache
import com.twitter.home_mixer.param.HomeMixerInjectionNames.UserAuthorEngagementCache
import com.twitter.home_mixer.param.HomeMixerInjectionNames.UserEngagementCache
import com.twitter.home_mixer.param.HomeMixerInjectionNames.UserTopicEngagementForNewUserCache
import com.twitter.home_mixer.util.InjectionTransformerImplicits._
import com.twitter.inject.TwitterModule
import com.twitter.ml.api.DataRecord
import com.twitter.ml.api.Feature
import com.twitter.ml.{api => ml}
import com.twitter.servo.cache.KeyValueTransformingReadCache
import com.twitter.servo.cache.Memcache
import com.twitter.servo.cache.ReadCache
import com.twitter.servo.util.Transformer
import com.twitter.storehaus_internal.memcache.MemcacheHelper
import com.twitter.summingbird.batch.Batcher
import com.twitter.summingbird_internal.bijection.BatchPairImplicits
import com.twitter.timelines.data_processing.ml_util.aggregation_framework.AggregationKey
import com.twitter.timelines.data_processing.ml_util.aggregation_framework.AggregationKeyInjection
import com.twitter.wtf.real_time_interaction_graph.{thriftscala => ig}
import javax.inject.Singleton
object RealtimeAggregateFeatureRepositoryModule
extends TwitterModule
with RealtimeAggregateHelpers {
private val authorIdFeature = new Feature.Discrete("entities.source_author_id").getFeatureId
private val countryCodeFeature = new Feature.Text("geo.user_location.country_code").getFeatureId
private val listIdFeature = new Feature.Discrete("list.id").getFeatureId
private val userIdFeature = new Feature.Discrete("meta.user_id").getFeatureId
private val topicIdFeature = new Feature.Discrete("entities.topic_id").getFeatureId
private val tweetIdFeature = new Feature.Discrete("entities.source_tweet_id").getFeatureId
@Provides
@Singleton
@Named(UserTopicEngagementForNewUserCache)
def providesUserTopicEngagementForNewUserCache(
@Named(TimelinesRealTimeAggregateClient) client: Memcache
): ReadCache[(Long, Long), ml.DataRecord] = {
new KeyValueTransformingReadCache(
client,
dataRecordValueTransformer,
keyTransformD2(userIdFeature, topicIdFeature)
)
}
@Provides
@Singleton
@Named(TwitterListEngagementCache)
def providesTwitterListEngagementCache(
@Named(TimelinesRealTimeAggregateClient) client: Memcache
): ReadCache[Long, ml.DataRecord] = {
new KeyValueTransformingReadCache(
client,
dataRecordValueTransformer,
keyTransformD1(listIdFeature)
)
}
@Provides
@Singleton
@Named(TopicEngagementCache)
def providesTopicEngagementCache(
@Named(TimelinesRealTimeAggregateClient) client: Memcache
): ReadCache[Long, ml.DataRecord] = {
new KeyValueTransformingReadCache(
client,
dataRecordValueTransformer,
keyTransformD1(topicIdFeature)
)
}
@Provides
@Singleton
@Named(UserAuthorEngagementCache)
def providesUserAuthorEngagementCache(
@Named(TimelinesRealTimeAggregateClient) client: Memcache
): ReadCache[(Long, Long), ml.DataRecord] = {
new KeyValueTransformingReadCache(
client,
dataRecordValueTransformer,
keyTransformD2(userIdFeature, authorIdFeature)
)
}
@Provides
@Singleton
@Named(UserEngagementCache)
def providesUserEngagementCache(
@Named(TimelinesRealTimeAggregateClient) client: Memcache
): ReadCache[Long, ml.DataRecord] = {
new KeyValueTransformingReadCache(
client,
dataRecordValueTransformer,
keyTransformD1(userIdFeature)
)
}
@Provides
@Singleton
@Named(TweetCountryEngagementCache)
def providesTweetCountryEngagementCache(
@Named(TimelinesRealTimeAggregateClient) client: Memcache
): ReadCache[(Long, String), ml.DataRecord] = {
new KeyValueTransformingReadCache(
client,
dataRecordValueTransformer,
keyTransformD1T1(tweetIdFeature, countryCodeFeature)
)
}
@Provides
@Singleton
@Named(TweetEngagementCache)
def providesTweetEngagementCache(
@Named(TimelinesRealTimeAggregateClient) client: Memcache
): ReadCache[Long, ml.DataRecord] = {
new KeyValueTransformingReadCache(
client,
dataRecordValueTransformer,
keyTransformD1(tweetIdFeature)
)
}
@Provides
@Singleton
@Named(EngagementsReceivedByAuthorCache)
def providesEngagementsReceivedByAuthorCache(
@Named(TimelinesRealTimeAggregateClient) client: Memcache
): ReadCache[Long, ml.DataRecord] = {
new KeyValueTransformingReadCache(
client,
dataRecordValueTransformer,
keyTransformD1(authorIdFeature)
)
}
@Provides
@Singleton
@Named(TopicCountryEngagementCache)
def providesTopicCountryEngagementCache(
@Named(TimelinesRealTimeAggregateClient) client: Memcache
): ReadCache[(Long, String), ml.DataRecord] = {
new KeyValueTransformingReadCache(
client,
dataRecordValueTransformer,
keyTransformD1T1(topicIdFeature, countryCodeFeature)
)
}
@Provides
@Singleton
@Named(RealTimeInteractionGraphUserVertexCache)
def providesRealTimeInteractionGraphUserVertexCache(
@Named(RealTimeInteractionGraphUserVertexClient) client: Memcache
): ReadCache[Long, ig.UserVertex] = {
val valueTransformer = BinaryScalaCodec(ig.UserVertex).toByteArrayTransformer()
val underlyingKey: Long => String = {
val cacheKeyPrefix = "user_vertex"
val defaultBatchID = Batcher.unit.currentBatch
val batchPairInjection = BatchPairImplicits.keyInjection(Injection.connect[Long, Array[Byte]])
MemcacheHelper
.keyEncoder(cacheKeyPrefix)(batchPairInjection)
.compose((k: Long) => (k, defaultBatchID))
}
new KeyValueTransformingReadCache(
client,
valueTransformer,
underlyingKey
)
}
}
trait RealtimeAggregateHelpers {
private def customKeyBuilder[K](prefix: String, f: K => Array[Byte]): K => String = {
// intentionally not implementing injection inverse because it is never used
def g(arr: Array[Byte]) = ???
MemcacheHelper.keyEncoder(prefix)(Injection.build(f)(g))
}
private val keyEncoder: AggregationKey => String = {
val cacheKeyPrefix = ""
val defaultBatchID = Batcher.unit.currentBatch
val batchPairInjection = BatchPairImplicits.keyInjection(AggregationKeyInjection)
customKeyBuilder(cacheKeyPrefix, batchPairInjection)
.compose((k: AggregationKey) => (k, defaultBatchID))
}
protected def keyTransformD1(f1: Long)(key: Long): String = {
val aggregationKey = AggregationKey(Map(f1 -> key), Map.empty)
keyEncoder(aggregationKey)
}
protected def keyTransformD2(f1: Long, f2: Long)(keys: (Long, Long)): String = {
val (k1, k2) = keys
val aggregationKey = AggregationKey(Map(f1 -> k1, f2 -> k2), Map.empty)
keyEncoder(aggregationKey)
}
protected def keyTransformD1T1(f1: Long, f2: Long)(keys: (Long, String)): String = {
val (k1, k2) = keys
val aggregationKey = AggregationKey(Map(f1 -> k1), Map(f2 -> k2))
keyEncoder(aggregationKey)
}
protected val dataRecordValueTransformer: Transformer[DataRecord, Array[Byte]] = ThriftCodec
.toCompact[ml.DataRecord]
.toByteArrayTransformer()
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/ScoredTweetsMemcacheModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.home_mixer.{thriftscala => t}
import com.twitter.inject.TwitterModule
import com.twitter.product_mixer.shared_library.memcached_client.MemcachedClientBuilder
import com.twitter.servo.cache.FinagleMemcache
import com.twitter.servo.cache.KeyTransformer
import com.twitter.servo.cache.KeyValueTransformingTtlCache
import com.twitter.servo.cache.Serializer
import com.twitter.servo.cache.ThriftSerializer
import com.twitter.servo.cache.TtlCache
import com.twitter.timelines.model.UserId
import org.apache.thrift.protocol.TCompactProtocol
import javax.inject.Singleton
object ScoredTweetsMemcacheModule extends TwitterModule {
private val ScopeName = "ScoredTweetsCache"
private val ProdDestName = "/srv#/prod/local/cache/home_scored_tweets:twemcaches"
private val StagingDestName = "/srv#/test/local/cache/twemcache_home_scored_tweets:twemcaches"
private val scoredTweetsSerializer: Serializer[t.ScoredTweetsResponse] =
new ThriftSerializer[t.ScoredTweetsResponse](
t.ScoredTweetsResponse,
new TCompactProtocol.Factory())
private val userIdKeyTransformer: KeyTransformer[UserId] = (userId: UserId) => userId.toString
@Singleton
@Provides
def providesScoredTweetsCache(
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): TtlCache[UserId, t.ScoredTweetsResponse] = {
val destName = serviceIdentifier.environment.toLowerCase match {
case "prod" => ProdDestName
case _ => StagingDestName
}
val client = MemcachedClientBuilder.buildMemcachedClient(
destName = destName,
numTries = 2,
numConnections = 1,
requestTimeout = 200.milliseconds,
globalTimeout = 400.milliseconds,
connectTimeout = 100.milliseconds,
acquisitionTimeout = 100.milliseconds,
serviceIdentifier = serviceIdentifier,
statsReceiver = statsReceiver.scope(ScopeName)
)
val underlyingCache = new FinagleMemcache(client)
new KeyValueTransformingTtlCache(
underlyingCache = underlyingCache,
transformer = scoredTweetsSerializer,
underlyingKey = userIdKeyTransformer
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/ScribeEventPublisherModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.clientapp.{thriftscala => ca}
import com.twitter.home_mixer.param.HomeMixerInjectionNames.CandidateFeaturesScribeEventPublisher
import com.twitter.home_mixer.param.HomeMixerInjectionNames.CommonFeaturesScribeEventPublisher
import com.twitter.home_mixer.param.HomeMixerInjectionNames.MinimumFeaturesScribeEventPublisher
import com.twitter.inject.TwitterModule
import com.twitter.logpipeline.client.EventPublisherManager
import com.twitter.logpipeline.client.common.EventPublisher
import com.twitter.logpipeline.client.serializers.EventLogMsgTBinarySerializer
import com.twitter.logpipeline.client.serializers.EventLogMsgThriftStructSerializer
import com.twitter.timelines.suggests.common.poly_data_record.{thriftjava => pldr}
import com.twitter.timelines.timeline_logging.{thriftscala => tl}
import javax.inject.Named
import javax.inject.Singleton
object ScribeEventPublisherModule extends TwitterModule {
val ClientEventLogCategory = "client_event"
val ServedCandidatesLogCategory = "home_timeline_served_candidates_flattened"
val ScoredCandidatesLogCategory = "home_timeline_scored_candidates"
val ServedCommonFeaturesLogCategory = "tq_served_common_features_offline"
val ServedCandidateFeaturesLogCategory = "tq_served_candidate_features_offline"
val ServedMinimumFeaturesLogCategory = "tq_served_minimum_features_offline"
@Provides
@Singleton
def providesClientEventsScribeEventPublisher: EventPublisher[ca.LogEvent] = {
val serializer = EventLogMsgThriftStructSerializer.getNewSerializer[ca.LogEvent]()
EventPublisherManager.buildScribeLogPipelinePublisher(ClientEventLogCategory, serializer)
}
@Provides
@Singleton
@Named(CommonFeaturesScribeEventPublisher)
def providesCommonFeaturesScribeEventPublisher: EventPublisher[pldr.PolyDataRecord] = {
val serializer = EventLogMsgTBinarySerializer.getNewSerializer
EventPublisherManager.buildScribeLogPipelinePublisher(
ServedCommonFeaturesLogCategory,
serializer)
}
@Provides
@Singleton
@Named(CandidateFeaturesScribeEventPublisher)
def providesCandidateFeaturesScribeEventPublisher: EventPublisher[pldr.PolyDataRecord] = {
val serializer = EventLogMsgTBinarySerializer.getNewSerializer
EventPublisherManager.buildScribeLogPipelinePublisher(
ServedCandidateFeaturesLogCategory,
serializer)
}
@Provides
@Singleton
@Named(MinimumFeaturesScribeEventPublisher)
def providesMinimumFeaturesScribeEventPublisher: EventPublisher[pldr.PolyDataRecord] = {
val serializer = EventLogMsgTBinarySerializer.getNewSerializer
EventPublisherManager.buildScribeLogPipelinePublisher(
ServedMinimumFeaturesLogCategory,
serializer)
}
@Provides
@Singleton
def providesServedCandidatesScribeEventPublisher: EventPublisher[tl.ServedEntry] = {
val serializer = EventLogMsgThriftStructSerializer.getNewSerializer[tl.ServedEntry]()
EventPublisherManager.buildScribeLogPipelinePublisher(ServedCandidatesLogCategory, serializer)
}
@Provides
@Singleton
def provideScoredCandidatesScribeEventPublisher: EventPublisher[tl.ScoredCandidate] = {
val serializer = EventLogMsgThriftStructSerializer.getNewSerializer[tl.ScoredCandidate]()
EventPublisherManager.buildScribeLogPipelinePublisher(ScoredCandidatesLogCategory, serializer)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/SimClustersRecentEngagementsClientModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.home_mixer.param.HomeMixerInjectionNames.BatchedStratoClientWithModerateTimeout
import com.twitter.inject.TwitterModule
import com.twitter.strato.client.Client
import com.twitter.timelines.clients.strato.twistly.SimClustersRecentEngagementSimilarityClient
import com.twitter.timelines.clients.strato.twistly.SimClustersRecentEngagementSimilarityClientImpl
import javax.inject.Named
import javax.inject.Singleton
object SimClustersRecentEngagementsClientModule extends TwitterModule {
@Singleton
@Provides
def providesSimilarityClient(
@Named(BatchedStratoClientWithModerateTimeout)
stratoClient: Client,
statsReceiver: StatsReceiver
): SimClustersRecentEngagementSimilarityClient = {
new SimClustersRecentEngagementSimilarityClientImpl(stratoClient, statsReceiver)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/StaleTweetsCacheModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.google.inject.name.Named
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.memcached.{Client => MemcachedClient}
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.hashing.KeyHasher
import com.twitter.home_mixer.param.HomeMixerInjectionNames.StaleTweetsCache
import com.twitter.inject.TwitterModule
import com.twitter.product_mixer.shared_library.memcached_client.MemcachedClientBuilder
import javax.inject.Singleton
object StaleTweetsCacheModule extends TwitterModule {
@Singleton
@Provides
@Named(StaleTweetsCache)
def providesCache(
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): MemcachedClient = {
MemcachedClientBuilder.buildMemcachedClient(
destName = "/srv#/prod/local/cache/staletweetscache:twemcaches",
numTries = 3,
numConnections = 1,
requestTimeout = 200.milliseconds,
globalTimeout = 500.milliseconds,
connectTimeout = 200.milliseconds,
acquisitionTimeout = 200.milliseconds,
serviceIdentifier = serviceIdentifier,
statsReceiver = statsReceiver,
failureAccrualPolicy = None,
keyHasher = Some(KeyHasher.FNV1_32)
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/ThriftFeatureRepositoryModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.conversions.PercentOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.finagle.thrift.ClientId
import com.twitter.graph_feature_service.{thriftscala => gfs}
import com.twitter.home_mixer.param.HomeMixerInjectionNames.EarlybirdRepository
import com.twitter.home_mixer.param.HomeMixerInjectionNames.GraphTwoHopRepository
import com.twitter.home_mixer.param.HomeMixerInjectionNames.InterestsThriftServiceClient
import com.twitter.home_mixer.param.HomeMixerInjectionNames.TweetypieContentRepository
import com.twitter.home_mixer.param.HomeMixerInjectionNames.UserFollowedTopicIdsRepository
import com.twitter.home_mixer.param.HomeMixerInjectionNames.UtegSocialProofRepository
import com.twitter.home_mixer.util.earlybird.EarlybirdRequestUtil
import com.twitter.home_mixer.util.tweetypie.RequestFields
import com.twitter.inject.TwitterModule
import com.twitter.interests.{thriftscala => int}
import com.twitter.product_mixer.shared_library.memcached_client.MemcachedClientBuilder
import com.twitter.product_mixer.shared_library.thrift_client.FinagleThriftClientBuilder
import com.twitter.product_mixer.shared_library.thrift_client.Idempotent
import com.twitter.recos.recos_common.{thriftscala => rc}
import com.twitter.recos.user_tweet_entity_graph.{thriftscala => uteg}
import com.twitter.search.earlybird.{thriftscala => eb}
import com.twitter.servo.cache.Cached
import com.twitter.servo.cache.CachedSerializer
import com.twitter.servo.cache.FinagleMemcacheFactory
import com.twitter.servo.cache.MemcacheCacheFactory
import com.twitter.servo.cache.NonLockingCache
import com.twitter.servo.cache.ThriftSerializer
import com.twitter.servo.keyvalue.KeyValueResultBuilder
import com.twitter.servo.repository.CachingKeyValueRepository
import com.twitter.servo.repository.ChunkingStrategy
import com.twitter.servo.repository.KeyValueRepository
import com.twitter.servo.repository.KeyValueResult
import com.twitter.servo.repository.keysAsQuery
import com.twitter.spam.rtf.{thriftscala => sp}
import com.twitter.tweetypie.{thriftscala => tp}
import com.twitter.util.Future
import com.twitter.util.Return
import javax.inject.Named
import javax.inject.Singleton
import org.apache.thrift.protocol.TCompactProtocol
object ThriftFeatureRepositoryModule extends TwitterModule {
private val DefaultRPCChunkSize = 50
private val GFSInteractionIdsLimit = 10
type EarlybirdQuery = (Seq[Long], Long)
type UtegQuery = (Seq[Long], (Long, Map[Long, Double]))
@Provides
@Singleton
@Named(InterestsThriftServiceClient)
def providesInterestsThriftServiceClient(
clientId: ClientId,
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): int.InterestsThriftService.MethodPerEndpoint = {
FinagleThriftClientBuilder
.buildFinagleMethodPerEndpoint[
int.InterestsThriftService.ServicePerEndpoint,
int.InterestsThriftService.MethodPerEndpoint](
serviceIdentifier = serviceIdentifier,
clientId = clientId,
dest = "/s/interests-thrift-service/interests-thrift-service",
label = "interests",
statsReceiver = statsReceiver,
idempotency = Idempotent(1.percent),
timeoutPerRequest = 350.milliseconds,
timeoutTotal = 350.milliseconds
)
}
@Provides
@Singleton
@Named(UserFollowedTopicIdsRepository)
def providesUserFollowedTopicIdsRepository(
@Named(InterestsThriftServiceClient) client: int.InterestsThriftService.MethodPerEndpoint
): KeyValueRepository[Seq[Long], Long, Seq[Long]] = {
val lookupContext = Some(
int.ExplicitInterestLookupContext(Some(Seq(int.InterestRelationType.Followed)))
)
def lookup(userId: Long): Future[Seq[Long]] = {
client.getUserExplicitInterests(userId, lookupContext).map { interests =>
interests.flatMap {
_.interestId match {
case int.InterestId.SemanticCore(semanticCoreInterest) => Some(semanticCoreInterest.id)
case _ => None
}
}
}
}
val keyValueRepository = toRepository(lookup)
keyValueRepository
}
@Provides
@Singleton
@Named(UtegSocialProofRepository)
def providesUtegSocialProofRepository(
clientId: ClientId,
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): KeyValueRepository[UtegQuery, Long, uteg.TweetRecommendation] = {
val client = FinagleThriftClientBuilder.buildFinagleMethodPerEndpoint[
uteg.UserTweetEntityGraph.ServicePerEndpoint,
uteg.UserTweetEntityGraph.MethodPerEndpoint](
serviceIdentifier = serviceIdentifier,
clientId = clientId,
dest = "/s/cassowary/user_tweet_entity_graph",
label = "uteg-social-proof-repo",
statsReceiver = statsReceiver,
idempotency = Idempotent(1.percent),
timeoutPerRequest = 150.milliseconds,
timeoutTotal = 250.milliseconds
)
val utegSocialProofTypes = Seq(
rc.SocialProofType.Favorite,
rc.SocialProofType.Retweet,
rc.SocialProofType.Reply
)
def lookup(
tweetIds: Seq[Long],
view: (Long, Map[Long, Double])
): Future[Seq[Option[uteg.TweetRecommendation]]] = {
val (userId, seedsWithWeights) = view
val socialProofRequest = uteg.SocialProofRequest(
requesterId = Some(userId),
seedsWithWeights = seedsWithWeights,
inputTweets = tweetIds,
socialProofTypes = Some(utegSocialProofTypes)
)
client.findTweetSocialProofs(socialProofRequest).map { result =>
val resultMap = result.socialProofResults.map(t => t.tweetId -> t).toMap
tweetIds.map(resultMap.get)
}
}
toRepositoryBatchWithView(lookup, chunkSize = 200)
}
@Provides
@Singleton
@Named(TweetypieContentRepository)
def providesTweetypieContentRepository(
clientId: ClientId,
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): KeyValueRepository[Seq[Long], Long, tp.Tweet] = {
val client = FinagleThriftClientBuilder
.buildFinagleMethodPerEndpoint[
tp.TweetService.ServicePerEndpoint,
tp.TweetService.MethodPerEndpoint](
serviceIdentifier = serviceIdentifier,
clientId = clientId,
dest = "/s/tweetypie/tweetypie",
label = "tweetypie-content-repo",
statsReceiver = statsReceiver,
idempotency = Idempotent(1.percent),
timeoutPerRequest = 300.milliseconds,
timeoutTotal = 500.milliseconds
)
def lookup(tweetIds: Seq[Long]): Future[Seq[Option[tp.Tweet]]] = {
val getTweetFieldsOptions = tp.GetTweetFieldsOptions(
tweetIncludes = RequestFields.ContentFields,
includeRetweetedTweet = false,
includeQuotedTweet = false,
forUserId = None,
safetyLevel = Some(sp.SafetyLevel.FilterNone),
visibilityPolicy = tp.TweetVisibilityPolicy.NoFiltering
)
val request = tp.GetTweetFieldsRequest(tweetIds = tweetIds, options = getTweetFieldsOptions)
client.getTweetFields(request).map { results =>
results.map {
case tp.GetTweetFieldsResult(_, tp.TweetFieldsResultState.Found(found), _, _) =>
Some(found.tweet)
case _ => None
}
}
}
val keyValueRepository = toRepositoryBatch(lookup, chunkSize = 20)
val cacheClient = MemcachedClientBuilder.buildRawMemcachedClient(
numTries = 1,
numConnections = 1,
requestTimeout = 200.milliseconds,
globalTimeout = 200.milliseconds,
connectTimeout = 200.milliseconds,
acquisitionTimeout = 200.milliseconds,
serviceIdentifier = serviceIdentifier,
statsReceiver = statsReceiver
)
val finagleMemcacheFactory =
FinagleMemcacheFactory(cacheClient, "/s/cache/home_content_features:twemcaches")
val cacheValueTransformer =
new ThriftSerializer[tp.Tweet](tp.Tweet, new TCompactProtocol.Factory())
val cachedSerializer = CachedSerializer.binary(cacheValueTransformer)
val cache = MemcacheCacheFactory(
memcache = finagleMemcacheFactory(),
ttl = 48.hours
)[Long, Cached[tp.Tweet]](cachedSerializer)
val lockingCache = new NonLockingCache(cache)
val cachedKeyValueRepository = new CachingKeyValueRepository(
keyValueRepository,
lockingCache,
keysAsQuery[Long]
)
cachedKeyValueRepository
}
@Provides
@Singleton
@Named(GraphTwoHopRepository)
def providesGraphTwoHopRepository(
clientId: ClientId,
serviceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): KeyValueRepository[(Seq[Long], Long), Long, Seq[gfs.IntersectionValue]] = {
val client = FinagleThriftClientBuilder
.buildFinagleMethodPerEndpoint[gfs.Server.ServicePerEndpoint, gfs.Server.MethodPerEndpoint](
serviceIdentifier = serviceIdentifier,
clientId = clientId,
dest = "/s/cassowary/graph_feature_service-server",
label = "gfs-repo",
statsReceiver = statsReceiver,
idempotency = Idempotent(1.percent),
timeoutPerRequest = 350.milliseconds,
timeoutTotal = 500.milliseconds
)
def lookup(
userIds: Seq[Long],
viewerId: Long
): Future[Seq[Option[Seq[gfs.IntersectionValue]]]] = {
val gfsIntersectionRequest = gfs.GfsPresetIntersectionRequest(
userId = viewerId,
candidateUserIds = userIds,
presetFeatureTypes = gfs.PresetFeatureTypes.HtlTwoHop,
intersectionIdLimit = Some(GFSInteractionIdsLimit)
)
client
.getPresetIntersection(gfsIntersectionRequest)
.map { graphFeatureServiceResponse =>
val resultMap = graphFeatureServiceResponse.results
.map(result => result.candidateUserId -> result.intersectionValues).toMap
userIds.map(resultMap.get(_))
}
}
toRepositoryBatchWithView(lookup, chunkSize = 200)
}
@Provides
@Singleton
@Named(EarlybirdRepository)
def providesEarlybirdSearchRepository(
client: eb.EarlybirdService.MethodPerEndpoint,
clientId: ClientId
): KeyValueRepository[EarlybirdQuery, Long, eb.ThriftSearchResult] = {
def lookup(
tweetIds: Seq[Long],
viewerId: Long
): Future[Seq[Option[eb.ThriftSearchResult]]] = {
val request = EarlybirdRequestUtil.getTweetsFeaturesRequest(
userId = Some(viewerId),
tweetIds = Some(tweetIds),
clientId = Some(clientId.name),
authorScoreMap = None,
tensorflowModel = Some("timelines_rectweet_replica")
)
client
.search(request).map { response =>
val resultMap = response.searchResults
.map(_.results.map { result => result.id -> result }.toMap).getOrElse(Map.empty)
tweetIds.map(resultMap.get)
}
}
toRepositoryBatchWithView(lookup)
}
protected def toRepository[K, V](
hydrate: K => Future[V]
): KeyValueRepository[Seq[K], K, V] = {
def asRepository(keys: Seq[K]): Future[KeyValueResult[K, V]] = {
Future.collect(keys.map(hydrate(_).liftToTry)).map { results =>
keys
.zip(results)
.foldLeft(new KeyValueResultBuilder[K, V]()) {
case (bldr, (k, result)) =>
result match {
case Return(v) => bldr.addFound(k, v)
case _ => bldr.addNotFound(k)
}
}.result
}
}
asRepository
}
protected def toRepositoryBatch[K, V](
hydrate: Seq[K] => Future[Seq[Option[V]]],
chunkSize: Int = DefaultRPCChunkSize
): KeyValueRepository[Seq[K], K, V] = {
def repository(keys: Seq[K]): Future[KeyValueResult[K, V]] =
batchRepositoryProcess(keys, hydrate(keys))
KeyValueRepository.chunked(repository, ChunkingStrategy.equalSize(chunkSize))
}
protected def toRepositoryBatchWithView[K, T, V](
hydrate: (Seq[K], T) => Future[Seq[Option[V]]],
chunkSize: Int = DefaultRPCChunkSize
): KeyValueRepository[(Seq[K], T), K, V] = {
def repository(input: (Seq[K], T)): Future[KeyValueResult[K, V]] = {
val (keys, view) = input
batchRepositoryProcess(keys, hydrate(keys, view))
}
KeyValueRepository.chunked(repository, CustomChunkingStrategy.equalSizeWithView(chunkSize))
}
private def batchRepositoryProcess[K, V](
keys: Seq[K],
f: Future[Seq[Option[V]]]
): Future[KeyValueResult[K, V]] = {
f.liftToTry
.map {
case Return(values) =>
keys
.zip(values)
.foldLeft(new KeyValueResultBuilder[K, V]()) {
case (bldr, (k, value)) =>
value match {
case Some(v) => bldr.addFound(k, v)
case _ => bldr.addNotFound(k)
}
}.result
case _ =>
keys
.foldLeft(new KeyValueResultBuilder[K, V]()) {
case (bldr, k) => bldr.addNotFound(k)
}.result
}
}
// Use only for cases not already covered by Servo's [[ChunkingStrategy]]
object CustomChunkingStrategy {
def equalSizeWithView[K, T](maxSize: Int): ((Seq[K], T)) => Seq[(Seq[K], T)] = {
case (keys, view) =>
ChunkingStrategy
.equalSize[K](maxSize)(keys)
.map { chunk: Seq[K] => (chunk, view) }
}
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/TimelinesPersistenceStoreClientModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.inject.TwitterModule
import com.twitter.inject.annotations.Flag
import com.twitter.timelinemixer.clients.persistence.TimelinePersistenceManhattanClientBuilder
import com.twitter.timelinemixer.clients.persistence.TimelinePersistenceManhattanClientConfig
import com.twitter.timelinemixer.clients.persistence.TimelineResponseBatchesClient
import com.twitter.timelinemixer.clients.persistence.TimelineResponseV3
import com.twitter.util.Duration
import javax.inject.Singleton
object TimelinesPersistenceStoreClientModule extends TwitterModule {
private val StagingDataset = "timeline_response_batches_v5_nonprod"
private val ProdDataset = "timeline_response_batches_v5"
private final val Timeout = "mh_persistence_store.timeout"
flag[Duration](Timeout, 300.millis, "Timeout per request")
@Provides
@Singleton
def providesTimelinesPersistenceStoreClient(
@Flag(Timeout) timeout: Duration,
injectedServiceIdentifier: ServiceIdentifier,
statsReceiver: StatsReceiver
): TimelineResponseBatchesClient[TimelineResponseV3] = {
val timelineResponseBatchesDataset =
injectedServiceIdentifier.environment.toLowerCase match {
case "prod" => ProdDataset
case _ => StagingDataset
}
val timelineResponseBatchesConfig = new TimelinePersistenceManhattanClientConfig {
val dataset = timelineResponseBatchesDataset
val isReadOnly = false
val serviceIdentifier = injectedServiceIdentifier
override val defaultMaxTimeout = timeout
override val maxRetryCount = 2
}
TimelinePersistenceManhattanClientBuilder.buildTimelineResponseV3BatchesClient(
timelineResponseBatchesConfig,
statsReceiver
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/TopicSocialProofClientModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.home_mixer.param.HomeMixerInjectionNames.BatchedStratoClientWithModerateTimeout
import com.twitter.inject.TwitterModule
import com.twitter.strato.client.Client
import com.twitter.timelines.clients.strato.topics.TopicSocialProofClient
import com.twitter.timelines.clients.strato.topics.TopicSocialProofClientImpl
import javax.inject.Named
import javax.inject.Singleton
object TopicSocialProofClientModule extends TwitterModule {
@Singleton
@Provides
def providesSimilarityClient(
@Named(BatchedStratoClientWithModerateTimeout)
stratoClient: Client,
statsReceiver: StatsReceiver
): TopicSocialProofClient = new TopicSocialProofClientImpl(stratoClient, statsReceiver)
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/TweetyPieClientModule.scala | package com.twitter.home_mixer.module
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.thrift.ClientId
import com.twitter.finagle.thriftmux.MethodBuilder
import com.twitter.finatra.mtls.thriftmux.modules.MtlsClient
import com.twitter.inject.Injector
import com.twitter.inject.annotations.Flags
import com.twitter.inject.thrift.modules.ThriftMethodBuilderClientModule
import com.twitter.stitch.tweetypie.TweetyPie
import com.twitter.tweetypie.thriftscala.TweetService
import com.twitter.util.Duration
import javax.inject.Singleton
/**
* Idempotent Tweetypie Thrift and Stitch client.
*/
object TweetypieClientModule
extends ThriftMethodBuilderClientModule[
TweetService.ServicePerEndpoint,
TweetService.MethodPerEndpoint
]
with MtlsClient {
private val TimeoutRequest = "tweetypie.timeout_request"
private val TimeoutTotal = "tweetypie.timeout_total"
flag[Duration](TimeoutRequest, 1000.millis, "Timeout per request")
flag[Duration](TimeoutTotal, 1000.millis, "Total timeout")
override val label: String = "tweetypie"
override val dest: String = "/s/tweetypie/tweetypie"
@Singleton
@Provides
def providesTweetypieStitchClient(tweetService: TweetService.MethodPerEndpoint): TweetyPie =
new TweetyPie(tweetService)
/**
* TweetyPie client id must be in the form of {service.env} or it will not be treated as an
* unauthorized client
*/
override protected def clientId(injector: Injector): ClientId = {
val serviceIdentifier = injector.instance[ServiceIdentifier]
ClientId(s"${serviceIdentifier.service}.${serviceIdentifier.environment}")
}
override protected def configureMethodBuilder(
injector: Injector,
methodBuilder: MethodBuilder
): MethodBuilder = {
val timeoutRequest = injector.instance[Duration](Flags.named(TimeoutRequest))
val timeoutTotal = injector.instance[Duration](Flags.named(TimeoutTotal))
methodBuilder
.withTimeoutPerRequest(timeoutRequest)
.withTimeoutTotal(timeoutTotal)
}
override protected def sessionAcquisitionTimeout: Duration = 500.millis
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/module/TweetypieStaticEntitiesCacheClientModule.scala | package com.twitter.home_mixer.module
import com.google.inject.name.Named
import com.google.inject.Provides
import com.twitter.conversions.DurationOps.RichDuration
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.home_mixer.param.HomeMixerInjectionNames.TweetypieStaticEntitiesCache
import com.twitter.inject.TwitterModule
import com.twitter.product_mixer.shared_library.memcached_client.MemcachedClientBuilder
import com.twitter.servo.cache.FinagleMemcache
import com.twitter.servo.cache.KeyTransformer
import com.twitter.servo.cache.KeyValueTransformingTtlCache
import com.twitter.servo.cache.ObservableTtlCache
import com.twitter.servo.cache.Serializer
import com.twitter.servo.cache.ThriftSerializer
import com.twitter.servo.cache.TtlCache
import com.twitter.tweetypie.{thriftscala => tp}
import javax.inject.Singleton
import org.apache.thrift.protocol.TCompactProtocol
object TweetypieStaticEntitiesCacheClientModule extends TwitterModule {
private val ScopeName = "TweetypieStaticEntitiesMemcache"
private val ProdDest = "/srv#/prod/local/cache/timelinescorer_tweet_core_data:twemcaches"
private val tweetsSerializer: Serializer[tp.Tweet] = {
new ThriftSerializer[tp.Tweet](tp.Tweet, new TCompactProtocol.Factory())
}
private val keyTransformer: KeyTransformer[Long] = { tweetId => tweetId.toString }
@Provides
@Singleton
@Named(TweetypieStaticEntitiesCache)
def providesTweetypieStaticEntitiesCache(
statsReceiver: StatsReceiver,
serviceIdentifier: ServiceIdentifier
): TtlCache[Long, tp.Tweet] = {
val memCacheClient = MemcachedClientBuilder.buildMemcachedClient(
destName = ProdDest,
numTries = 1,
numConnections = 1,
requestTimeout = 50.milliseconds,
globalTimeout = 100.milliseconds,
connectTimeout = 100.milliseconds,
acquisitionTimeout = 100.milliseconds,
serviceIdentifier = serviceIdentifier,
statsReceiver = statsReceiver
)
mkCache(new FinagleMemcache(memCacheClient), statsReceiver)
}
private def mkCache(
finagleMemcache: FinagleMemcache,
statsReceiver: StatsReceiver
): TtlCache[Long, tp.Tweet] = {
val baseCache: KeyValueTransformingTtlCache[Long, String, tp.Tweet, Array[Byte]] =
new KeyValueTransformingTtlCache(
underlyingCache = finagleMemcache,
transformer = tweetsSerializer,
underlyingKey = keyTransformer
)
ObservableTtlCache(
underlyingCache = baseCache,
statsReceiver = statsReceiver.scope(ScopeName),
windowSize = 1000,
name = ScopeName
)
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/param/BUILD.bazel | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
strict_deps = True,
tags = ["bazel-compatible"],
dependencies = [
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/product",
],
)
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/param/GlobalParamConfigModule.scala | package com.twitter.home_mixer.param
import com.twitter.inject.TwitterModule
import com.twitter.product_mixer.core.functional_component.configapi.registry.GlobalParamConfig
object GlobalParamConfigModule extends TwitterModule {
override def configure(): Unit = {
bind[GlobalParamConfig].to[HomeGlobalParamConfig]
}
}
|
the-algorithm-main/home-mixer/server/src/main/scala/com/twitter/home_mixer/param/HomeGlobalParamConfig.scala | package com.twitter.home_mixer.param
import com.twitter.home_mixer.param.HomeGlobalParams._
import com.twitter.product_mixer.core.functional_component.configapi.registry.GlobalParamConfig
import javax.inject.Inject
import javax.inject.Singleton
/**
* Register Params that do not relate to a specific product. See GlobalParamConfig -> ParamConfig
* for hooks to register Params based on type.
*/
@Singleton
class HomeGlobalParamConfig @Inject() () extends GlobalParamConfig {
override val booleanFSOverrides = Seq(
AdsDisableInjectionBasedOnUserRoleParam,
EnableAdvertiserBrandSafetySettingsFeatureHydratorParam,
EnableImpressionBloomFilter,
EnableNahFeedbackInfoParam,
EnableNewTweetsPillAvatarsParam,
EnableScribeServedCandidatesParam,
EnableSendScoresToClient,
EnableSocialContextParam,
)
override val boundedIntFSOverrides = Seq(
MaxNumberReplaceInstructionsParam,
TimelinesPersistenceStoreMaxEntriesPerClient,
)
override val boundedDoubleFSOverrides = Seq(
ImpressionBloomFilterFalsePositiveRateParam
)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.