pjfanning commented on code in PR #385: URL: https://github.com/apache/incubator-pekko/pull/385#discussion_r1226470742
########## actor/src/main/scala/org/apache/pekko/io/dns/IdGenerator.scala: ########## @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * license agreements; and to You under the Apache License, version 2.0: + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * This file is part of the Apache Pekko project, derived from Akka. + */ + +package org.apache.pekko.io.dns + +import org.apache.pekko.annotation.InternalApi + +import java.security.SecureRandom +import java.util.concurrent.ThreadLocalRandom +import java.util.concurrent.atomic.AtomicInteger + +/** + * INTERNAL API + * + * These are called by an actor, however they are called inside composed futures so need to be + * nextId needs to be thread safe. + */ +@InternalApi +private[pekko] trait IdGenerator { + def nextId(): Short +} + +/** + * INTERNAL API + */ +@InternalApi +private[pekko] object IdGenerator { + sealed trait Policy + + object Policy { + case object Sequence extends Policy + case object ThreadLocalRandom extends Policy + case object SecureRandom extends Policy + val Default: Policy = ThreadLocalRandom + + def apply(name: String): Option[Policy] = name.toLowerCase match { + case "sequence" => Some(Sequence) + case "thread-local-random" => Some(ThreadLocalRandom) + case "secure-random" => Some(SecureRandom) + case _ => Some(ThreadLocalRandom) + } + } + + def apply(policy: Policy): IdGenerator = policy match { + case Policy.Sequence => sequence() + case Policy.ThreadLocalRandom => random(ThreadLocalRandom.current()) + case Policy.SecureRandom => random(new SecureRandom()) + } + + /** + * @return a random sequence of ids for production + */ + def random(rand: java.util.Random): IdGenerator = new IdGenerator { + override def nextId(): Short = rand.nextInt(Short.MaxValue).toShort + } + + /** + * @return a predictable sequence of ids for tests + */ + def sequence(): IdGenerator = new IdGenerator { + val requestId: AtomicInteger = new AtomicInteger(0) + + override def nextId(): Short = { + val oldId = requestId.get() + val newId = (oldId + 1) % Short.MaxValue + + if (requestId.compareAndSet(oldId, newId.intValue())) { + newId.toShort + } else { + nextId() Review Comment: Could this function be marked `@tailrec`? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
