-
Notifications
You must be signed in to change notification settings - Fork 29
/
AsynchronousIo.scala
164 lines (148 loc) · 6.31 KB
/
AsynchronousIo.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package com.thoughtworks.dsl
package keywords
import java.net.SocketAddress
import java.nio.ByteBuffer
import java.nio.channels._
import com.thoughtworks.dsl.Dsl.{!!, Keyword}
import scala.util.control.NonFatal
/** The base keyword to perform asynchronous IO in [[domains.task.Task]]s.
*
* @example The following `readAll` is a [[com.thoughtworks.dsl.domains.task.Task Task]] to read file content
* with the help of [[AsynchronousIo.ReadFile]]
*
* {{{
* import java.nio._, file._, channels._
* import com.thoughtworks.dsl.domains.task.Task
* import com.thoughtworks.dsl.keywords._
* import com.thoughtworks.dsl.keywords.Shift._
* import com.thoughtworks.dsl.keywords.AsynchronousIo.ReadFile
* import scala.collection.mutable.ArrayBuffer
* import scala.io.Codec
* def readAll(channel: AsynchronousFileChannel, temporaryBufferSize: Int = 4096): Task[ArrayBuffer[CharBuffer]] = Task {
* val charBuffers = ArrayBuffer.empty[CharBuffer]
* val decoder = Codec.UTF8.decoder
* val byteBuffer = ByteBuffer.allocate(temporaryBufferSize)
* var position: Long = 0L
* while (!ReadFile(channel, byteBuffer, position) != -1) {
* position += byteBuffer.position()
* byteBuffer.flip()
* charBuffers += decoder.decode(byteBuffer)
* byteBuffer.clear()
* }
* charBuffers
* }
* }}}
*
* `Task`s created from !-notation can be used in `for`-comprehension,
* and other keywords can be used together in the same `for` block.
*
* For example, the following `cat` function contains a single `for` block to concatenate file contents.
* It asynchronously iterates elements `Seq`, `ArrayBuffer` and `String` with the help of [[keywords.Each]],
* managed native resources with the help of [[keywords.Using]],
* performs previously created `readAll` task with the help of [[keywords.Shift]],
* and finally converts the return type [[comprehension.ComprehensionOps.as as]] a `Task[Vector[Char]]`.
*
* {{{
* import com.thoughtworks.dsl.comprehension._
* import com.thoughtworks.dsl.keywords._
* import com.thoughtworks.dsl.keywords.Shift._
* import com.thoughtworks.dsl.domains.task.Task
* import java.net.URL
* def cat(paths: Path*) = {
* for {
* path <- Each(paths)
* channel <- Using(AsynchronousFileChannel.open(path))
* charBuffers <- readAll(channel)
* charBuffer <- Each(charBuffers)
* char <- Each(charBuffer.toString)
* } yield char
* }.as[Task[Vector[Char]]]
* }}}
*
* Then the `cat` function is used to concatenate files from this project, as shown below:
*
* {{{
* Task.toFuture(Task {
* (!cat(Paths.get(".sbtopts"), Paths.get(".scalafmt.conf"))).mkString should be(
* "-J-XX:MaxMetaspaceSize=512M\n-J-Xmx5G\n-J-Xss6M\nversion = \"1.5.1\"\nmaxColumn = 120"
* )
* })
* }}}
*/
trait AsynchronousIo[Value] extends Any with Keyword[AsynchronousIo[Value], Value] {
/** Starts the asynchronous operations */
protected def start[Attachment](attachment: Attachment, handler: CompletionHandler[Value, _ >: Attachment]): Unit
}
object AsynchronousIo {
final case class Connect(socket: AsynchronousSocketChannel, remote: SocketAddress) extends AsynchronousIo[Void] {
protected def start[Attachment](attachment: Attachment, handler: CompletionHandler[Void, _ >: Attachment]): Unit = {
socket.connect(remote, attachment, handler)
}
}
final case class Accept(socket: AsynchronousServerSocketChannel)
extends AnyVal
with AsynchronousIo[AsynchronousSocketChannel] {
protected def start[Attachment](
attachment: Attachment,
handler: CompletionHandler[AsynchronousSocketChannel, _ >: Attachment]
): Unit = {
socket.accept(attachment, handler)
}
}
final case class ReadFile(channel: AsynchronousFileChannel, destination: ByteBuffer, position: Long)
extends AsynchronousIo[Integer] {
protected def start[Attachment](
attachment: Attachment,
handler: CompletionHandler[Integer, _ >: Attachment]
): Unit = {
channel.read(destination, position, attachment, handler)
}
}
final case class WriteFile(channel: AsynchronousFileChannel, source: ByteBuffer, position: Long)
extends AsynchronousIo[Integer] {
protected def start[Attachment](
attachment: Attachment,
handler: CompletionHandler[Integer, _ >: Attachment]
): Unit = {
channel.write(source, position, attachment, handler)
}
}
final case class Read(channel: AsynchronousByteChannel, destination: ByteBuffer) extends AsynchronousIo[Integer] {
protected def start[Attachment](
attachment: Attachment,
handler: CompletionHandler[Integer, _ >: Attachment]
): Unit = {
channel.read(destination, attachment, handler)
}
}
final case class Write(channel: AsynchronousByteChannel, source: ByteBuffer) extends AsynchronousIo[Integer] {
private[dsl] def destination = source
protected def start[Attachment](
attachment: Attachment,
handler: CompletionHandler[Integer, _ >: Attachment]
): Unit = {
channel.write(source, attachment, handler)
}
}
private def completionHandler[Value](successHandler: Value => (Unit !! Throwable)) = {
new CompletionHandler[Value, Throwable => Unit] {
def failed(exc: Throwable, failureHandler: Throwable => Unit): Unit = {
failureHandler(exc)
}
def completed(result: Value, failureHandler: Throwable => Unit): Unit = {
val protectedContinuation =
try {
successHandler(result)
} catch {
case NonFatal(e) =>
val () = failureHandler(e)
return
}
protectedContinuation(failureHandler)
}
}
}
implicit def asynchronousIoDsl[Value]: Dsl[AsynchronousIo[Value], Unit !! Throwable, Value] = { (keyword, handler) =>
keyword.start(_, completionHandler(handler))
}
}