-
-
Notifications
You must be signed in to change notification settings - Fork 23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
team ingestor #240
Merged
Merged
team ingestor #240
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
0894447
Initial effort to implement team ingestor
lenguyenthanh a12bed4
TeamIngestor basically works
lenguyenthanh 8e290dc
Minor refactor and comments tweak
lenguyenthanh 9bebe1e
With delete event, We don't have full document
lenguyenthanh c79bcd0
Only fetch interested fields and clean up
lenguyenthanh 4fccc39
Refactor deleteMany out of ingestors
lenguyenthanh 203af56
Add drop for team ingestor
lenguyenthanh ace4d7a
code tweak
lenguyenthanh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
package lila.search | ||
package ingestor | ||
|
||
import cats.effect.IO | ||
import cats.syntax.all.* | ||
import com.mongodb.client.model.changestream.FullDocument | ||
import com.mongodb.client.model.changestream.OperationType.* | ||
import lila.search.spec.TeamSource | ||
import mongo4cats.bson.Document | ||
import mongo4cats.database.MongoDatabase | ||
import mongo4cats.models.collection.ChangeStreamDocument | ||
import mongo4cats.operations.{ Aggregate, Filter, Projection } | ||
import org.typelevel.log4cats.Logger | ||
import org.typelevel.log4cats.syntax.* | ||
|
||
import java.time.Instant | ||
import scala.concurrent.duration.* | ||
|
||
trait TeamIngestor: | ||
// watch change events from MongoDB and ingest team data into elastic search | ||
def watch: fs2.Stream[IO, Unit] | ||
|
||
object TeamIngestor: | ||
|
||
private val index = Index.Team | ||
|
||
private val interestedOperations = List(DELETE, INSERT, UPDATE, REPLACE).map(_.getValue) | ||
private val eventFilter = Filter.in("operationType", interestedOperations) | ||
|
||
private val interestedFields = List("_id", F.name, F.description, F.nbMembers, F.name, F.enabled) | ||
|
||
private val interestedEventFields = | ||
List("operationType", "clusterTime", "documentKey._id") ++ interestedFields.map("fullDocument." + _) | ||
private val eventProjection = Projection.include(interestedEventFields) | ||
|
||
private val aggregate = Aggregate.matchBy(eventFilter).combinedWith(Aggregate.project(eventProjection)) | ||
|
||
def apply(mongo: MongoDatabase[IO], elastic: ESClient[IO], store: KVStore, config: IngestorConfig.Team)( | ||
using Logger[IO] | ||
): IO[TeamIngestor] = | ||
mongo.getCollection("team").map(apply(elastic, store, config)) | ||
|
||
def apply(elastic: ESClient[IO], store: KVStore, config: IngestorConfig.Team)(teams: MongoCollection)(using | ||
Logger[IO] | ||
): TeamIngestor = new: | ||
def watch = | ||
fs2.Stream | ||
.eval(startAt.flatTap(since => info"Starting team ingestor from $since")) | ||
.flatMap: last => | ||
changeStream(last) | ||
.filterNot(_.isEmpty) | ||
.evalMap: events => | ||
val lastEventTimestamp = events.lastOption.flatMap(_.clusterTime).flatMap(_.asInstant) | ||
val (toDelete, toIndex) = events.partition(_.isDelete) | ||
storeBulk(toIndex.flatten(_.fullDocument)) | ||
*> elastic.deleteMany(index, toDelete) | ||
*> saveLastIndexedTimestamp(lastEventTimestamp.getOrElse(Instant.now)) | ||
|
||
private def storeBulk(docs: List[Document]): IO[Unit] = | ||
val sources = docs.toSources | ||
info"Received ${docs.size} teams to index" *> | ||
elastic.storeBulk(index, sources) *> info"Indexed ${sources.size} teams" | ||
.handleErrorWith: e => | ||
Logger[IO].error(e)(s"Failed to index teams: ${docs.map(_.id).mkString(", ")}") | ||
|
||
private def saveLastIndexedTimestamp(time: Instant): IO[Unit] = | ||
store.put(index.value, time) | ||
*> info"Stored last indexed time ${time.getEpochSecond} for $index" | ||
|
||
private def startAt: IO[Option[Instant]] = | ||
config.startAt.fold(store.get(index.value))(Instant.ofEpochSecond(_).some.pure[IO]) | ||
|
||
private def changeStream(since: Option[Instant]): fs2.Stream[IO, List[ChangeStreamDocument[Document]]] = | ||
// skip the first event if we're starting from a specific timestamp | ||
// since the event at that timestamp is already indexed | ||
val skip = since.fold(0)(_ => 1) | ||
val builder = teams.watch(aggregate) | ||
since | ||
.fold(builder)(x => builder.startAtOperationTime(x.asBsonTimestamp)) | ||
.batchSize(config.batchSize) | ||
.fullDocument(FullDocument.UPDATE_LOOKUP) // this is required for update event | ||
.boundedStream(config.batchSize) | ||
.drop(skip) | ||
.evalTap(x => debug"Team change stream event: $x") | ||
.groupWithin(config.batchSize, config.timeWindows.second) | ||
.map(_.toList) | ||
|
||
extension (docs: List[Document]) | ||
private def toSources: List[(String, TeamSource)] = | ||
docs.flatten(doc => (doc.id, doc.toSource).mapN(_ -> _)) | ||
|
||
extension (doc: Document) | ||
private def toSource: Option[TeamSource] = | ||
( | ||
doc.getString(F.name), | ||
doc.getString(F.description), | ||
doc.getInt(F.nbMembers) | ||
).mapN(TeamSource.apply) | ||
|
||
private def isEnabled = | ||
doc.getBoolean(F.enabled).getOrElse(true) | ||
|
||
extension (event: ChangeStreamDocument[Document]) | ||
private def isDelete: Boolean = | ||
event.operationType == DELETE || | ||
event.fullDocument.fold(false)(x => !x.isEnabled) | ||
|
||
object F: | ||
val name = "name" | ||
val description = "description" | ||
val nbMembers = "nbMembers" | ||
val enabled = "enabled" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
.exists(