Skip to content

Commit

Permalink
LF: Deprecate com.daml.lf.data.TryOps.Bracket (#10249)
Browse files Browse the repository at this point in the history
* LF: Deprecate com.daml.lf.data.TryOps.Bracket

CHANGELOG_BEGIN
CHANGELOG_END

* address reviews

* fix
  • Loading branch information
remyhaemmerle-da authored Jul 13, 2021
1 parent b59f365 commit e4d7cd7
Show file tree
Hide file tree
Showing 9 changed files with 50 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,19 @@
package com.daml.lf
package archive

import com.daml.lf.data.Bytes

import java.io.InputStream
import java.util.jar.{Attributes, Manifest}

import scala.util.{Failure, Success, Try}
import scala.util.{Failure, Success, Try, Using}

object DarManifestReader {

private val supportedFormat = "daml-lf"

def dalfNames(bytes: Bytes): Try[Dar[String]] =
Using.resource(bytes.toInputStream)(dalfNames)

def dalfNames(is: InputStream): Try[Dar[String]] = {
val manifest = new Manifest(is)
val attributes = value(manifest.getMainAttributes) _
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,20 @@ package com.daml.lf.archive

import com.daml.daml_lf_dev.DamlLf
import com.daml.lf.data.Bytes
import com.daml.lf.data.TryOps.Bracket.bracket
import com.daml.lf.data.TryOps.sequence

import java.io.{File, FileInputStream, IOException, InputStream}
import java.util.zip.ZipInputStream
import scala.util.control.NonFatal
import scala.util.{Failure, Success, Try}
import scala.util.{Failure, Success, Try, Using}

class GenDarReader[A](parseDalf: Bytes => Try[A]) {

import GenDarReader._

/** Reads an archive from a File. */
def readArchiveFromFile(darFile: File): Try[Dar[A]] =
bracket(Try(new ZipInputStream(new FileInputStream(darFile))))(zis => Try(zis.close))
.flatMap(readArchive(darFile.getName, _))
Using(new ZipInputStream(new FileInputStream(darFile)))(readArchive(darFile.getName, _)).flatten

/** Reads an archive from a ZipInputStream. The stream will be closed by this function! */
def readArchive(
Expand All @@ -44,10 +42,10 @@ class GenDarReader[A](parseDalf: Bytes => Try[A]) {
entrySizeThreshold: Int,
): (String, Bytes) = {
val buffSize = 4 * 1024 // 4k
val buffer = new Array[Byte](buffSize)
val buffer = Array.ofDim[Byte](buffSize)
var output = Bytes.Empty
Iterator.continually(zip.read(buffer)).takeWhile(_ >= 0).foreach { size =>
output = output ++ Bytes.fromByteArray(buffer, 0, size)
output ++= Bytes.fromByteArray(buffer, 0, size)
if (output.length >= entrySizeThreshold) throw Error.ZipBomb()
}
name -> output
Expand Down Expand Up @@ -90,7 +88,7 @@ object GenDarReader {
}

private[GenDarReader] def readDalfNames: Try[Dar[String]] =
bracket(get(ManifestName).map(_.toInputStream))(is => Try(is.close()))
get(ManifestName)
.flatMap(DarManifestReader.dalfNames)
.recoverWith { case NonFatal(e1) => Failure(Error.InvalidDar(this, e1)) }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ package archive
import java.io.{File, FileInputStream, InputStream}
import java.util.zip.ZipInputStream

import scala.util.{Failure, Success, Try}
import com.daml.lf.data.TryOps.Bracket.bracket
import scala.util.{Failure, Success, Try, Using}

/** Can parse DARs and DALFs.
*/
Expand All @@ -20,20 +19,18 @@ case class UniversalArchiveReader(
/** Reads a DAR from a File. */
def readFile(file: File): Try[Dar[ArchivePayload]] =
supportedFileType(file).flatMap {
case DarFile => readDarStream(file.getName, new ZipInputStream(new FileInputStream(file)))
case DalfFile => readDalfStream(new FileInputStream(file))
case DarFile =>
Using(new ZipInputStream(new FileInputStream(file)))(readDarStream(file.getName, _)).flatten
case DalfFile => Using(new FileInputStream(file))(readDalfStream)
}

/** Reads a DAR from an InputStream. This method takes care of closing the stream! */
def readDarStream(fileName: String, dar: ZipInputStream): Try[Dar[ArchivePayload]] =
bracket(Try(dar))(dar => Try(dar.close()))
.flatMap(DarReader.readArchive(fileName, _, entrySizeThreshold))
DarReader.readArchive(fileName, dar, entrySizeThreshold)

/** Reads a DALF from an InputStream. This method takes care of closing the stream! */
def readDalfStream(dalf: InputStream): Try[Dar[ArchivePayload]] =
bracket(Try(dalf))(dalf => Try(dalf.close()))
.flatMap(is => Try(Reader.readArchive(is)))
.map(Dar(_, List.empty))
def readDalfStream(dalf: InputStream): Dar[ArchivePayload] =
Dar(Reader.readArchive(dalf), List.empty)

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ private[daml] object TryOps {
b <- tb
} yield f(a, b)

@deprecated("use scala.util.Using", since = "1.16.0")
object Bracket {

/** The following description borrowed from https://hackage.haskell.org/package/exceptions-0.10.1/docs/Control-Monad-Catch.html#v:bracket
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import com.daml.lf.data.TryOps.Bracket.bracket

import scala.util.{Failure, Success, Try}

@deprecated("Bracket is deprecated; use scala.util.Using instead", since = "1.16.0")
class TryOpsTest extends AnyWordSpec with Matchers with ScalaCheckDrivenPropertyChecks {

"bracket should call clean after successful calculation" in forAll { (a: Int, b: Int) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@ import java.io.{BufferedWriter, File, FileWriter}
import akka.http.scaladsl.model.HttpResponse
import akka.stream.Materializer
import akka.util.ByteString
import com.daml.lf.data.TryOps.Bracket.bracket
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.{ExecutionContext, Future}
import scala.io.Source
import scala.util.{Failure, Success, Try}
import scala.util.{Failure, Success, Try, Using}

object TestUtil extends LazyLogging {

Expand All @@ -25,11 +24,9 @@ object TestUtil extends LazyLogging {
}

def writeToFile(file: File, text: String): Try[File] =
bracket(Try(new BufferedWriter(new FileWriter(file))))(x => Try(x.close())).flatMap { bw =>
Try {
bw.write(text)
file
}
Using(new BufferedWriter(new FileWriter(file))) { bw =>
bw.write(text)
file
}

def readFile(resourcePath: String): String =
Expand Down
19 changes: 6 additions & 13 deletions ledger-service/jwt/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@ da_scala_library(
],
scalacopts = lf_scalacopts,
tags = ["maven_coordinates=com.daml:jwt:__VERSION__"],
versioned_scala_deps = {
"2.12": [
"@maven//:org_scala_lang_modules_scala_collection_compat",
],
},
visibility = ["//visibility:public"],
runtime_deps = [
"@maven//:ch_qos_logback_logback_classic",
],
deps = [
"//daml-lf/data",
"@maven//:com_auth0_java_jwt",
"@maven//:com_auth0_jwks_rsa",
"@maven//:com_google_guava_guava",
Expand All @@ -34,24 +38,13 @@ da_scala_library(

da_scala_binary(
name = "jwt-bin",
srcs = glob(["src/main/scala/**/*.scala"]),
main_class = "com.daml.jwt.Main",
scala_deps = [
"@maven//:com_github_scopt_scopt",
"@maven//:com_typesafe_scala_logging_scala_logging",
"@maven//:org_scalaz_scalaz_core",
],
scalacopts = lf_scalacopts,
runtime_deps = [
":jwt",
"@maven//:ch_qos_logback_logback_classic",
],
deps = [
"//daml-lf/data",
"@maven//:com_auth0_java_jwt",
"@maven//:com_auth0_jwks_rsa",
"@maven//:com_google_guava_guava",
"@maven//:org_slf4j_slf4j_api",
":jwt",
],
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@ import java.security.interfaces.{ECPublicKey, RSAPrivateKey, RSAPublicKey}
import java.security.spec.PKCS8EncodedKeySpec
import java.security.KeyFactory

import com.daml.lf.data.TryOps.Bracket.bracket
import scalaz.Show
import scalaz.syntax.show._

import scala.util.Try
import scala.util.{Try, Using}

object KeyUtils {
final case class Error(what: Symbol, message: String)
Expand All @@ -30,32 +29,26 @@ object KeyUtils {
/** Reads an RSA public key from a X509 encoded file.
* These usually have the .crt file extension.
*/
def readRSAPublicKeyFromCrt(file: File): Try[RSAPublicKey] = {
bracket(Try(new FileInputStream(file)))(is => Try(is.close())).flatMap { istream =>
Try(
CertificateFactory
.getInstance("X.509")
.generateCertificate(istream)
.getPublicKey
.asInstanceOf[RSAPublicKey]
)
}
}
def readRSAPublicKeyFromCrt(file: File): Try[RSAPublicKey] =
Using(new FileInputStream(file))(
CertificateFactory
.getInstance("X.509")
.generateCertificate(_)
.getPublicKey
.asInstanceOf[RSAPublicKey]
)

/** Reads an EC public key from a X509 encoded file.
* These usually have the .crt file extension.
*/
def readECPublicKeyFromCrt(file: File): Try[ECPublicKey] = {
bracket(Try(new FileInputStream(file)))(is => Try(is.close())).flatMap { istream =>
Try(
CertificateFactory
.getInstance("X.509")
.generateCertificate(istream)
.getPublicKey
.asInstanceOf[ECPublicKey]
)
}
}
def readECPublicKeyFromCrt(file: File): Try[ECPublicKey] =
Using(new FileInputStream(file))(
CertificateFactory
.getInstance("X.509")
.generateCertificate(_)
.getPublicKey
.asInstanceOf[ECPublicKey]
)

/** Reads a RSA private key from a PEM/PKCS#8 file.
* These usually have the .pem file extension.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ package com.daml.jwt

import java.io.{File, FileNotFoundException, FileOutputStream}

import com.daml.lf.data.TryOps.Bracket.bracket
import scalaz.std.option._
import scalaz.syntax.applicative._

import scala.util.{Failure, Success, Try}
import scala.util.{Failure, Success, Try, Using}

object RsaKeysGenerator {

Expand Down Expand Up @@ -41,15 +40,8 @@ object RsaKeysGenerator {
}

private def writeKey(key: Array[Byte], file: File): Try[File] =
bracket(Try(new FileOutputStream(file)))(close).flatMap { ostream =>
for {
encoder <- Try(java.util.Base64.getEncoder)
_ <- Try(ostream.write(encoder.encode(key)))
_ <- exists(file)
} yield file
}

private def close(a: FileOutputStream): Try[Unit] = Try(a.close())
Using(new FileOutputStream(file))(_.write(java.util.Base64.getEncoder.encode(key)))
.flatMap(_ => exists(file))

private def exists(f: File): Try[File] =
for {
Expand Down

0 comments on commit e4d7cd7

Please sign in to comment.