Skip to content

Commit

Permalink
remove A.unit, also scala tweaks
Browse files Browse the repository at this point in the history
apparently we no longer need to explicitely return a Unit
  • Loading branch information
ornicar committed Jul 12, 2023
1 parent ff9393d commit f10a055
Show file tree
Hide file tree
Showing 128 changed files with 695 additions and 896 deletions.
2 changes: 1 addition & 1 deletion app/Env.scala
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ final class EnvBoot(
export netConfig.{ domain, baseUrl }

// eagerly load the Uptime object to fix a precise date
lila.common.Uptime.startedAt.unit
lila.common.Uptime.startedAt

// wire all the lila modules
lazy val memo: lila.memo.Env = wire[lila.memo.Env]
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Account.scala
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ final class Account(
case Some(user) =>
env.report.api.reopenReports(lila.report.Suspect(user)) >>
auth.authenticateUser(user, remember = true) andDo
lila.mon.user.auth.reopenConfirm("success").increment().unit
lila.mon.user.auth.reopenConfirm("success").increment()
}

def data = Auth { _ ?=> me ?=>
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Auth.scala
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ final class Auth(
case Some(user) =>
authLog(user.username, none, "Magic link")
authenticateUser(user, remember = true) andDo
lila.mon.user.auth.magicLinkConfirm("success").increment().unit
lila.mon.user.auth.magicLinkConfirm("success").increment()
}

def makeLoginToken = AuthOrScoped(_.Web.Login) { ctx ?=> me ?=>
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Clas.scala
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ final class Clas(env: Env, authC: Auth) extends LilaController(env):
env.msg.api
.multiPost(Source(students.map(_.user.id)), full)
.addEffect: nb =>
lila.mon.msg.clasBulk(clas.id.value).record(nb).unit
lila.mon.msg.clasBulk(clas.id.value).record(nb)
.inject(redirectTo(clas).flashSuccess)
}
)
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Fishnet.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ final class Fishnet(env: Env) extends LilaController(env):
def acquire(slow: Boolean = false) =
ClientAction[JsonApi.Request.Acquire] { _ => client =>
api.acquire(client, slow) addEffect { jobOpt =>
lila.mon.fishnet.http.request(jobOpt.isDefined).increment().unit
lila.mon.fishnet.http.request(jobOpt.isDefined).increment()
} map Right.apply
}

Expand Down
2 changes: 1 addition & 1 deletion app/controllers/LilaController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ abstract private[controllers] class LilaController(val env: Env)
)

def pageHit(using req: RequestHeader): Unit =
if HTTPRequest.isHuman(req) then lila.mon.http.path(req.path).increment().unit
if HTTPRequest.isHuman(req) then lila.mon.http.path(req.path).increment()

def LangPage(call: Call)(f: Context ?=> Fu[Result])(langCode: String): EssentialAction =
LangPage(call.url)(f)(langCode)
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/Team.scala
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ final class Team(
full
)
.addEffect: nb =>
lila.mon.msg.teamBulk(team.id).record(nb).unit
lila.mon.msg.teamBulk(team.id).record(nb)
// we don't wait for the stream to complete, it would make lichess time out
fuccess(Result.Through)
}(Result.Limited)
Expand Down
37 changes: 18 additions & 19 deletions modules/activity/src/main/Env.scala
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,19 @@ final class Env(

lila.common.Bus.subscribeFuns(
"finishGame" -> {
case lila.game.actorApi.FinishGame(game, _) if !game.aborted => write.game(game).unit
case lila.game.actorApi.FinishGame(game, _) if !game.aborted => write.game(game)
},
"finishPuzzle" -> { case res: lila.puzzle.Puzzle.UserResult =>
write.puzzle(res).unit
write.puzzle(res)
},
"stormRun" -> { case lila.hub.actorApi.puzzle.StormRun(userId, score) =>
write.storm(userId, score).unit
write.storm(userId, score)
},
"racerRun" -> { case lila.hub.actorApi.puzzle.RacerRun(userId, score) =>
write.racer(userId, score).unit
write.racer(userId, score)
},
"streakRun" -> { case lila.hub.actorApi.puzzle.StreakRun(userId, score) =>
write.streak(userId, score).unit
write.streak(userId, score)
}
)

Expand All @@ -64,19 +64,18 @@ final class Env(
"startStudy",
"streamStart",
"swissFinish"
) {
case lila.forum.CreatePost(post) => write.forumPost(post).unit
case lila.ublog.UblogPost.Create(post) => write.ublogPost(post).unit
case prog: lila.practice.PracticeProgress.OnComplete => write.practice(prog).unit
case lila.simul.Simul.OnStart(simul) => write.simul(simul).unit
case CorresMoveEvent(move, Some(userId), _, _, false) => write.corresMove(move.gameId, userId).unit
case lila.hub.actorApi.plan.MonthInc(userId, months) => write.plan(userId, months).unit
case lila.hub.actorApi.relation.Follow(from, to) => write.follow(from, to).unit
):
case lila.forum.CreatePost(post) => write.forumPost(post)
case lila.ublog.UblogPost.Create(post) => write.ublogPost(post)
case prog: lila.practice.PracticeProgress.OnComplete => write.practice(prog)
case lila.simul.Simul.OnStart(simul) => write.simul(simul)
case CorresMoveEvent(move, Some(userId), _, _, false) => write.corresMove(move.gameId, userId)
case lila.hub.actorApi.plan.MonthInc(userId, months) => write.plan(userId, months)
case lila.hub.actorApi.relation.Follow(from, to) => write.follow(from, to)
case lila.study.actorApi.StartStudy(id) =>
// wait some time in case the study turns private
scheduler.scheduleOnce(5 minutes) { write.study(id).unit }.unit
case lila.hub.actorApi.team.CreateTeam(id, _, userId) => write.team(id, userId).unit
case lila.hub.actorApi.team.JoinTeam(id, userId) => write.team(id, userId).unit
case lila.hub.actorApi.streamer.StreamStart(userId, _) => write.streamStart(userId).unit
case lila.swiss.SwissFinish(swissId, ranking) => write.swiss(swissId, ranking).unit
}
scheduler.scheduleOnce(5 minutes) { write.study(id) }
case lila.hub.actorApi.team.CreateTeam(id, _, userId) => write.team(id, userId)
case lila.hub.actorApi.team.JoinTeam(id, userId) => write.team(id, userId)
case lila.hub.actorApi.streamer.StreamStart(userId, _) => write.streamStart(userId)
case lila.swiss.SwissFinish(swissId, ranking) => write.swiss(swissId, ranking)
2 changes: 1 addition & 1 deletion modules/analyse/src/main/Env.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ final class Env(
lazy val externalEngine = ExternalEngineApi(db(CollName("external_engine")), cacheApi)

lila.common.Bus.subscribeFun("oauth") { case lila.hub.actorApi.oauth.TokenRevoke(id) =>
externalEngine onTokenRevoke id unit
externalEngine onTokenRevoke id
}
4 changes: 2 additions & 2 deletions modules/api/src/main/AccountClosure.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ final class AccountClosure(

Bus.subscribeFuns(
"garbageCollect" -> { case lila.hub.actorApi.security.GarbageCollect(userId) =>
(modApi.garbageCollect(userId) >> lichessClose(userId)).unit
(modApi.garbageCollect(userId) >> lichessClose(userId))
},
"rageSitClose" -> { case lila.hub.actorApi.playban.RageSitClose(userId) => lichessClose(userId).unit }
"rageSitClose" -> { case lila.hub.actorApi.playban.RageSitClose(userId) => lichessClose(userId) }
)

def close(u: User)(using me: Me): Funit = for
Expand Down
4 changes: 2 additions & 2 deletions modules/api/src/main/Env.scala
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ final class Env(
promise completeWith chatFreshness.of(source)
},
"announce" -> {
case Announce(msg, date, _) if msg contains "will restart" => pagerDuty.lilaRestart(date).unit
case Announce(msg, date, _) if msg contains "will restart" => pagerDuty.lilaRestart(date)
},
"lpv" -> {
case AllPgnsFromText(text, p) => p completeWith textLpvExpand.allPgnsFromText(text)
Expand All @@ -129,7 +129,7 @@ final class Env(
)

scheduler.scheduleWithFixedDelay(1 minute, 1 minute): () =>
lila.mon.bus.classifiers.update(lila.common.Bus.size()).unit
lila.mon.bus.classifiers.update(lila.common.Bus.size())
lila.mon.jvm.threads()
// ensure the Lichess user is online
socketEnv.remoteSocket.onlineUserIds.getAndUpdate(_ + User.lichessId)
Expand Down
12 changes: 5 additions & 7 deletions modules/api/src/main/EventStream.scala
Original file line number Diff line number Diff line change
Expand Up @@ -82,24 +82,22 @@ final class EventStream(
// gotta send a message to check if the client has disconnected
queue offer None
self ! SetOnline
.unit

case StartGame(game) => queue.offer(gameJson(game, "gameStart")).unit
case StartGame(game) => queue.offer(gameJson(game, "gameStart"))

case FinishGame(game, _) => queue.offer(gameJson(game, "gameFinish")).unit
case FinishGame(game, _) => queue.offer(gameJson(game, "gameFinish"))

case lila.challenge.Event.Create(c) if isMyChallenge(c) =>
val json = challengeJson("challenge")(c) ++ challengeCompat(c)
lila.common.LilaFuture // give time for anon challenger to load the challenge page
.delay(if c.challengerIsAnon then 2.seconds else 0.seconds):
queue.offer(json.some).void
.unit

case lila.challenge.Event.Decline(c) if isMyChallenge(c) =>
queue.offer(challengeJson("challengeDeclined")(c).some).unit
queue.offer(challengeJson("challengeDeclined")(c).some)

case lila.challenge.Event.Cancel(c) if isMyChallenge(c) =>
queue.offer(challengeJson("challengeCanceled")(c).some).unit
queue.offer(challengeJson("challengeCanceled")(c).some)

// pretend like the rematch is a challenge
case lila.hub.actorApi.round.RematchOffer(gameId) =>
Expand All @@ -121,7 +119,7 @@ final class EventStream(
.foreach:
_.foreach: c =>
val json = challengeJson("challengeCanceled")(c) ++ challengeCompat(c)
queue.offer(json.some).unit
queue.offer(json.some)

private def isMyChallenge(c: Challenge) =
me.is(c.destUserId) || me.is(c.challengerUserId)
Expand Down
7 changes: 3 additions & 4 deletions modules/bookmark/src/main/Env.scala
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,9 @@ final class Env(
system.actorOf(
Props(
new Actor:
def receive = {
case Toggle(gameId, userId) => api.toggle(gameId, userId).unit
case Remove(gameId) => api.removeByGameId(gameId).unit
}
def receive =
case Toggle(gameId, userId) => api.toggle(gameId, userId)
case Remove(gameId) => api.removeByGameId(gameId)
),
name = config.actorName
)
19 changes: 9 additions & 10 deletions modules/bot/src/main/GameStateStream.scala
Original file line number Diff line number Diff line change
Expand Up @@ -101,18 +101,18 @@ final class GameStateStream(
context.system.scheduler.scheduleOnce(if gameOver then 10 second else 1 second):
Bus.publish(Tell(init.game.id.value, BotConnected(as, v = false)), "roundSocket")
queue.complete()
lila.mon.bot.gameStream("stop").increment().unit
lila.mon.bot.gameStream("stop").increment()

def receive =
case MoveGameEvent(g, _, _) if g.id == id && !g.finished => pushState(g).unit
case MoveGameEvent(g, _, _) if g.id == id && !g.finished => pushState(g)
case lila.chat.ChatLine(chatId, UserLine(username, _, _, text, false, false)) =>
pushChatLine(username, text, chatId.value.lengthIs == GameId.size).unit
case FinishGame(g, _) if g.id == id => onGameOver(g.some).unit
case AbortedBy(pov) if pov.gameId == id => onGameOver(pov.game.some).unit
case BoardDrawOffer(g) if g.id == id => pushState(g).unit
case BoardTakebackOffer(g) if g.id == id => pushState(g).unit
case BoardTakeback(g) if g.id == id => pushState(g).unit
case BoardGone(pov, seconds) if pov.gameId == id && pov.color != as => opponentGone(seconds).unit
pushChatLine(username, text, chatId.value.lengthIs == GameId.size)
case FinishGame(g, _) if g.id == id => onGameOver(g.some)
case AbortedBy(pov) if pov.gameId == id => onGameOver(pov.game.some)
case BoardDrawOffer(g) if g.id == id => pushState(g)
case BoardTakebackOffer(g) if g.id == id => pushState(g)
case BoardTakeback(g) if g.id == id => pushState(g)
case BoardGone(pov, seconds) if pov.gameId == id && pov.color != as => opponentGone(seconds)
case SetOnline =>
onlineApiUsers.setOnline(user.id)
context.system.scheduler
Expand All @@ -121,7 +121,6 @@ final class GameStateStream(
queue offer None
self ! SetOnline
Bus.publish(Tell(id.value, QuietFlag), "roundSocket")
.unit

def pushState(g: Game): Funit =
jsonView gameState Game.WithInitialFen(g, init.fen) dmap some flatMap queue.offer void
Expand Down
2 changes: 1 addition & 1 deletion modules/challenge/src/main/ChallengeBulk.scala
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ final class ChallengeBulkApi(
.toMat(LilaStream.sinkCount)(Keep.right)
.run()
.addEffect { nb =>
lila.mon.api.challenge.bulk.createNb(bulk.by.value).increment(nb).unit
lila.mon.api.challenge.bulk.createNb(bulk.by.value).increment(nb)
} >> {
if bulk.startClocksAt.isDefined
then coll.updateField($id(bulk._id), "pairedAt", nowInstant)
Expand Down
34 changes: 17 additions & 17 deletions modules/challenge/src/main/ChallengeKeepAliveStream.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ final class ChallengeKeepAliveStream(api: ChallengeApi)(using
):
def apply(challenge: Challenge, initialJson: JsObject): Source[JsValue, ?] =
Source(List(initialJson)) concat
Source.queue[JsObject](1, akka.stream.OverflowStrategy.dropHead).mapMaterializedValue { queue =>
val keepAliveInterval = scheduler.scheduleWithFixedDelay(15 seconds, 15 seconds) { () =>
api.ping(challenge.id).unit
}
def completeWith(msg: String) = {
queue.offer(Json.obj("done" -> msg)) andDo queue.complete()
}.unit
val sub = Bus.subscribeFun("challenge") {
case Event.Accept(c, _) if c.id == challenge.id => completeWith("accepted")
case Event.Cancel(c) if c.id == challenge.id => completeWith("canceled")
case Event.Decline(c) if c.id == challenge.id => completeWith("declined")
}
queue.watchCompletion().addEffectAnyway {
keepAliveInterval.cancel()
Bus.unsubscribe(sub, "challenge")
}
}
Source
.queue[JsObject](1, akka.stream.OverflowStrategy.dropHead)
.mapMaterializedValue: queue =>
val keepAliveInterval = scheduler.scheduleWithFixedDelay(15 seconds, 15 seconds): () =>
api.ping(challenge.id)
def completeWith(msg: String) =
queue.offer(Json.obj("done" -> msg)) andDo queue.complete()
val sub = Bus.subscribeFun("challenge"):
case Event.Accept(c, _) if c.id == challenge.id => completeWith("accepted")
case Event.Cancel(c) if c.id == challenge.id => completeWith("canceled")
case Event.Decline(c) if c.id == challenge.id => completeWith("declined")

queue
.watchCompletion()
.addEffectAnyway:
keepAliveInterval.cancel()
Bus.unsubscribe(sub, "challenge")
4 changes: 2 additions & 2 deletions modules/challenge/src/main/Env.scala
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,10 @@ final class Env(
val forms = new ChallengeForm

system.scheduler.scheduleWithFixedDelay(10 seconds, 3343 millis): () =>
api.sweep.unit
api.sweep

system.scheduler.scheduleWithFixedDelay(20 seconds, 2897 millis): () =>
bulk.tick.unit
bulk.tick

private class ChallengeColls(db: lila.db.Db):
val challenge = db(CollName("challenge"))
Expand Down
6 changes: 3 additions & 3 deletions modules/chat/src/main/ChatApi.scala
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ final class ChatApi(
lila.mon.chat
.message(publicSource.fold("player")(_.parentName), line.troll)
.increment()
.unit

publish(chatId, ChatLine(chatId, line), busChan)
else
logger.info(s"Link check rejected $line in $publicSource")
Expand Down Expand Up @@ -132,7 +132,7 @@ final class ChatApi(
publish(chatId, ChatLine(chatId, line), busChan)

def service(chatId: ChatId, text: String, busChan: BusChan.Select, isVolatile: Boolean): Unit =
(if isVolatile then volatile else system) (chatId, text, busChan).unit
(if isVolatile then volatile else system) (chatId, text, busChan)

def timeout(
chatId: ChatId,
Expand Down Expand Up @@ -274,7 +274,7 @@ final class ChatApi(
makeLine(chatId, color, text).so: line =>
persistLine(chatId, line).andDo:
publish(chatId, ChatLine(chatId, line), busChan)
lila.mon.chat.message("anonPlayer", troll = false).increment().unit
lila.mon.chat.message("anonPlayer", troll = false).increment()

private def makeLine(chatId: ChatId, color: Color, t1: String): Option[Line] =
Writer.preprocessUserInput(t1, none) flatMap { t2 =>
Expand Down
14 changes: 5 additions & 9 deletions modules/clas/src/main/ClasStudentCache.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,22 @@ final class ClasStudentCache(colls: ClasColls)(using scheduler: Scheduler)(using
def addStudent(userId: UserId): Unit = bloomFilter add userId.value

private def rebuildBloomFilter(): Unit =
colls.student.countAll foreach { count =>
colls.student.countAll.foreach: count =>
val nextBloom = BloomFilter[String](count + 1, falsePositiveRate)
colls.student
.find($doc("archived" $exists false), $doc("userId" -> true, "_id" -> false).some)
.cursor[Bdoc](ReadPref.priTemp)
.documentSource()
.throttle(300, 1.second)
.toMat(Sink.fold[Int, Bdoc](0) { case (counter, doc) =>
.runWith(Sink.fold[Int, Bdoc](0): (counter, doc) =>
if counter % 500 == 0 then logger.info(s"ClasStudentCache.rebuild $counter")
doc.string("userId") foreach nextBloom.add
counter + 1
})(Keep.right)
.run()
.addEffect { nb =>
)
.addEffect: nb =>
lila.mon.clas.student.bloomFilter.count.update(nb)
bloomFilter.dispose()
bloomFilter = nextBloom
}
.monSuccess(_.clas.student.bloomFilter.fu)
.unit
}

scheduler.scheduleWithFixedDelay(71.seconds, 24.hours) { (() => rebuildBloomFilter()) }.unit
scheduler.scheduleWithFixedDelay(71.seconds, 24.hours) { (() => rebuildBloomFilter()) }
9 changes: 2 additions & 7 deletions modules/clas/src/main/Env.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,7 @@ final class Env(
authenticator: lila.user.Authenticator,
cacheApi: lila.memo.CacheApi,
baseUrl: BaseUrl
)(using
ec: Executor,
scheduler: Scheduler,
mat: akka.stream.Materializer,
mode: play.api.Mode
):
)(using Executor, Scheduler, akka.stream.Materializer, play.api.Mode):

lazy val nameGenerator: NameGenerator = wire[NameGenerator]

Expand All @@ -47,7 +42,7 @@ final class Env(

lila.common.Bus.subscribeFuns(
"finishGame" -> { case lila.game.actorApi.FinishGame(game, _) =>
progressApi.onFinishGame(game).unit
progressApi.onFinishGame(game)
},
"clas" -> {
case lila.hub.actorApi.clas.IsTeacherOf(teacher, student, promise) =>
Expand Down
Loading

0 comments on commit f10a055

Please sign in to comment.