forked from lichess-org/lila-ws
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge remote-tracking branch 'origin/ws-toilet' into ws-toilet
- Loading branch information
Showing
3 changed files
with
43 additions
and
0 deletions.
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,41 @@ | ||
package lila.ws | ||
package util | ||
|
||
import org.apache.pekko.actor.typed.Scheduler | ||
import reactivemongo.api.bson.* | ||
|
||
/* A setting that is read from the database every `ttl`. | ||
* | ||
* Usage: | ||
* val nbDogs: Setting[Int] = settingStore.makeSetting("dogs", 48, 1.minute) | ||
* println("dogs: " + nbDogs.get) | ||
* | ||
* Note that the first reads are not guaranteed to be from the DB, | ||
* but could return the hardcoded default value instead. | ||
* | ||
* To change the value of a setting, you need to update the DB directly, using mongosh: | ||
* db.setting.updateOne({_id:'dogs'},{$set:{value:50}}) | ||
*/ | ||
|
||
case class Setting[A](default: A, ttl: FiniteDuration)(fetch: () => Future[Option[A]])(using | ||
ec: Executor, | ||
scheduler: Scheduler | ||
): | ||
private var value: A = default | ||
|
||
def get: A = value | ||
|
||
private def readFromDb(): Unit = | ||
fetch().foreach: opt => | ||
value = opt | default | ||
|
||
scheduler.scheduleWithFixedDelay(1.millis, ttl)(() => readFromDb()) | ||
|
||
final class SettingStore(mongo: Mongo)(using Executor, Scheduler): | ||
|
||
def makeSetting[A: BSONReader](key: String, default: A, ttl: FiniteDuration = 10.seconds): Setting[A] = | ||
Setting[A](default, ttl): () => | ||
mongo.settingColl.flatMap: | ||
_.find(selector = BSONDocument("_id" -> key)) | ||
.one[BSONDocument] | ||
.map(_.flatMap(_.getAsOpt[A]("value"))) |