-
Notifications
You must be signed in to change notification settings - Fork 29
/
AsynchronousIo.scala
198 lines (183 loc) · 6.75 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package com.thoughtworks.dsl
package keywords
import java.net.SocketAddress
import java.nio.ByteBuffer
import java.nio.channels._
import com.thoughtworks.dsl.Dsl.IsKeyword
import scala.util.control.NonFatal
import scala.annotation.unchecked.uncheckedVariance
/** The base keyword to perform asynchronous IO in [[domains.task.Task]]s.
*
* @example
* The following `readAll` is a [[com.thoughtworks.dsl.domains.Task Task]] to
* read file content with the help of [[AsynchronousIo.ReadFile]]
*
* {{{
* import java.nio._, file._, channels._
* import com.thoughtworks.dsl.domains.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._
* import com.thoughtworks.dsl.keywords._
* import com.thoughtworks.dsl.domains.Task
* import java.net.URL
* def cat(paths: Path*) = Each.ToView {
* for {
* path <- Each(paths)
* channel <- Using(AsynchronousFileChannel.open(path))
* charBuffers <- Shift(readAll(channel))
* charBuffer <- Each(charBuffers)
* char <- Each(charBuffer.toString)
* } yield char
* }.to[Task]
* }}}
*
* Then the `cat` function is used to concatenate files from this project, as
* shown below:
*
* {{{
* Task.toFuture(Task {
* val filesToRead = for (fileName <- Seq(".sbtopts", ".scalafmt.conf")) yield {
* Paths.get(sourcecode.File()).getParent.resolve("../../../../../..").resolve(fileName)
* }
* (!Shift(cat(filesToRead: _*))).mkString should be(
* filesToRead.map { fileToRead =>
* new String(Files.readAllBytes(fileToRead), io.Codec.UTF8.charSet)
* }.mkString
* )
* })
* }}}
*/
trait AsynchronousIo[+Value] extends Any with Dsl.Keyword.Trait {
/** Starts the asynchronous operations */
protected def start[Attachment](
attachment: Attachment,
// CompletionHandler is essentially covariant even though Java does not
// support covariance
handler: CompletionHandler[Value @uncheckedVariance, _ >: Attachment]
): Unit
}
object AsynchronousIo {
given [Keyword <: AsynchronousIo[Value], Value]: IsKeyword[Keyword, Value]
with {}
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)
}
}
}
given [Value]: Dsl.Original[AsynchronousIo[Value], Unit !! Throwable, Value] =
Dsl.Original { (keyword, handler) =>
keyword.start(_, completionHandler(handler))
}
}