This repository has been archived by the owner on May 21, 2018. It is now read-only.
/
modes.scala
294 lines (225 loc) · 11.1 KB
/
modes.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/******************************************************************************************************************\
* Rapture Core, version 2.0.0. Copyright 2010-2015 Jon Pretty, Propensive Ltd. *
* *
* The primary distribution site is http://rapture.io/ *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in complance *
* with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed *
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License *
* for the specific language governing permissions and limitations under the License. *
\******************************************************************************************************************/
package rapture.core
import language.higherKinds
import language.experimental.macros
import scala.annotation._
import scala.reflect._
import scala.reflect.macros._
import reflect.runtime.universe.WeakTypeTag
import scala.util._
import scala.concurrent._
trait MethodConstraint
object Mode extends Mode_1 {
abstract class Import[M[G <: MethodConstraint] <: Mode[G]] {
def apply[G <: MethodConstraint](): M[G] = modeImplicit[G]
implicit def modeImplicit[G <: MethodConstraint]: M[G] = mode[G]
protected def mode[G <: MethodConstraint]: M[G]
}
}
@implicitNotFound(msg = "No implicit mode was available for ${Group} methods. "+
"Please import a member of rapture.core.modes, e.g. modes.throwExceptions.")
trait Mode[+Group <: MethodConstraint] { mode =>
type Wrap[+_, _ <: Exception]
def wrap[Result, E <: Exception](blk: => Result): Wrap[Result, E]
def flatWrap[Result, E <: Exception: ClassTag](blk: => Wrap[Result, E]): Wrap[Result, E] =
wrap(unwrap(blk))
var callPath = "_"
def unwrap[Result](value: => Wrap[Result, _ <: Exception]): Result
def unwrap[Result](value: => Wrap[Result, _ <: Exception], path: String): Result = {
val oldCallPath = callPath
callPath += path
val res = unwrap[Result](value)
callPath = oldCallPath
res
}
def generic[C <: MethodConstraint]: Mode[C] { type Wrap[+T, E <: Exception] = mode.Wrap[T, E] } =
this.asInstanceOf[Mode[C] { type Wrap[+T, E <: Exception] = mode.Wrap[T, E] }]
def compose[Group2 <: MethodConstraint](mode2: Mode[Group2]) = new Mode[Group] {
type Wrap[+Result, E <: Exception] = mode.Wrap[mode2.Wrap[Result, E], E]
def wrap[Result, E <: Exception](blk: => Result): Wrap[Result, E] =
mode.wrap(mode2.wrap(blk))
def unwrap[Return](value: => Wrap[Return, _ <: Exception]): Return =
mode2.unwrap(mode.unwrap(value))
}
def catching[E <: Exception: ClassTag, T](blk: => T) = try blk catch {
case e: E => exception(e)
case e: Exception => throw e
}
def safe[T](blk: => T): T = {
try blk catch { case e: Exception => exception(e) }
}
def exception[T, E <: Exception: ClassTag](e: E, continue: Boolean = true): T = throw e
def wrapEither[Result, E <: Exception: ClassTag](blk: => Either[E, Result]): Wrap[Result, E] =
wrap {
blk match {
case Left(e) => throw e
case Right(r) => r
}
}
def wrapOption[Result](blk: => Option[Result]): Wrap[Result, Exception] = wrap(blk.get)
def wrapTry[Result, E <: Exception: ClassTag](blk: => Try[Result]): Wrap[Result, E] =
wrap(blk.get)
}
object repl {
var showStackTraces: Boolean = false
private var lastExceptionValue: Throwable = new SilentException
def lastException: Nothing = throw lastExceptionValue
implicit def modeImplicit[Group <: MethodConstraint] = new Repl[Group]
class SilentException extends Throwable {
override def printStackTrace(pw: java.io.PrintWriter) = ()
}
class Repl[+Group <: MethodConstraint] extends Mode[Group] {
type Wrap[+Return, E <: Exception] = Return
def wrap[Return, E <: Exception](blk: => Return): Return = try blk catch {
case e: Exception => if(showStackTraces) throw e else {
Console.println("Execution failed with exception: "+e.toString)
Console.print("For the full stacktrace, see repl.lastException.")
lastExceptionValue = e
throw new SilentException()
}
}
def unwrap[Return](value: => Wrap[Return, _ <: Exception]): Return = value
}
}
package modes {
object throwExceptions extends Mode.Import[ThrowExceptionsMode] {
protected def mode[G <: MethodConstraint] = new ThrowExceptionsMode[G]
}
object explicit extends Mode.Import[ExplicitMode] {
protected def mode[G <: MethodConstraint] = new ExplicitMode[G]
}
/*object returnEither extends Mode.Import[ReturnEitherMode] {
protected def mode[G <: MethodConstraint] = new ReturnEitherMode[G]
}*/
object returnResult extends Mode.Import[ReturnResultMode] {
protected def mode[G <: MethodConstraint] = new ReturnResultMode[G]
}
object returnTry extends Mode.Import[ReturnTryMode] {
protected def mode[G <: MethodConstraint] = new ReturnTryMode[G]
}
object exponentialBackoff extends Mode.Import[ExponentialBackoffMode] {
protected def mode[G <: MethodConstraint] = new ExponentialBackoffMode[G]()
}
object keepCalmAndCarryOn extends Mode.Import[KeepCalmAndCarryOnMode] {
protected def mode[G <: MethodConstraint] = new KeepCalmAndCarryOnMode[G]()
}
object returnOption extends Mode.Import[ReturnOptionMode] {
protected def mode[G <: MethodConstraint] = new ReturnOptionMode[G]()
}
object returnFuture {
implicit def modeImplicit[G <: MethodConstraint](implicit ec: ExecutionContext) =
new ReturnFutureMode[G]
def apply[G <: MethodConstraint](implicit ec: ExecutionContext) = modeImplicit[G]
}
object timeExecution {
implicit def modeImplicit[D: TimeSystem.ByDuration, G <: MethodConstraint] =
new TimeExecution[D, G]
def apply[D: TimeSystem.ByDuration, G <: MethodConstraint] = modeImplicit[D, G]
}
class Explicit[+Result, E <: Exception](blk: => Result) {
def get: Result = blk
def opt: Option[Result] = returnOption[Nothing].wrap(blk)
def getOrElse[Result2 >: Result](t: Result2): Result2 = opt.getOrElse(blk)
//def either: Either[E, Result] = returnEither[Nothing].wrap(blk)
def attempt: Try[Result] = returnTry[Nothing].wrap(blk)
def backoff(maxRetries: Int = 10, initialPause: Long = 1000L,
backoffRate: Double = 2.0): Result =
new ExponentialBackoffMode(maxRetries, initialPause, backoffRate).wrap(blk)
def time[D: TimeSystem.ByDuration] = timeExecution[D, Nothing].wrap(blk)
def future(implicit ec: ExecutionContext): Future[Result] = returnFuture[Nothing].wrap(blk)
override def toString = "<unevaluated result>"
}
}
private[core] trait Mode_1 {
implicit def defaultMode: ThrowExceptionsMode[Nothing] = new ThrowExceptionsMode
}
private[core] class ThrowExceptionsMode[+G <: MethodConstraint] extends Mode[G] {
type Wrap[+T, E <: Exception] = T
def wrap[T, E <: Exception](t: => T): T = t
def unwrap[Return](value: => Wrap[Return, _ <: Exception]): Return = value
}
private[core] class ExplicitMode[+G <: MethodConstraint] extends Mode[G] {
type Wrap[+T, E <: Exception] = modes.Explicit[T, E]
def wrap[T, E <: Exception](t: => T): modes.Explicit[T, E] =
new modes.Explicit[T, E](t)
def unwrap[Return](value: => Wrap[Return, _ <: Exception]): Return = value.get
}
/*private[core] class ReturnEitherMode[+Group <: MethodConstraint] extends Mode[Group] {
type Wrap[+Result, E <: Exception] = Either[E, Result]
def wrap[Result, E <: Exception](blk: => Result): Either[E, Result] = {
try Right(blk) catch {
case e: Throwable => if(implicitly[WeakTypeTag[E]].isTypeOf(e)) Left(e.asInstanceOf[E]) else throw e
}
}
def unwrap[Return](value: => Either[_ <: Exception, Return]): Return = value.right.get
override def toString = "[modes.returnEither]"
}*/
private[core] class ReturnTryMode[+G <: MethodConstraint] extends Mode[G] {
type Wrap[+T, E <: Exception] = Try[T]
def wrap[T, E <: Exception](t: => T): Try[T] = Try(t)
def unwrap[Return](value: => Wrap[Return, _ <: Exception]): Return = value.get
override def toString = "[modes.returnTry]"
}
private[core] class ExponentialBackoffMode[+G <: MethodConstraint](maxRetries: Int = 10, initialPause: Long = 1000L,
backoffRate: Double = 2.0) extends Mode[G] {
type Wrap[+T, E <: Exception] = T
def wrap[T, E <: Exception](t: => T): T = {
var multiplier = 1.0
var count = 1
var result: T = null.asInstanceOf[T]
var exception: Exception = null.asInstanceOf[Exception]
while(result == null && count < maxRetries) try { result = t } catch {
case e: Exception =>
exception = e
import timeSystems.numeric._
Thread.sleep((multiplier*initialPause).toLong)
multiplier *= backoffRate
count += 1
}
if(result != null) result else throw exception
}
def unwrap[Return](value: => Wrap[Return, _ <: Exception]): Return = value
}
private[core] class KeepCalmAndCarryOnMode[+G <: MethodConstraint] extends Mode[G] {
type Wrap[+T, E <: Exception] = T
def wrap[T, E <: Exception](t: => T): T =
try t catch { case e: Exception => null.asInstanceOf[T] }
def unwrap[Return](value: => Wrap[Return, _ <: Exception]): Return = Option[Return](value).get
override def toString = "[modes.kcaco]"
}
private[core] class ReturnOptionMode[+G <: MethodConstraint] extends Mode[G] {
type Wrap[+T, E <: Exception] = Option[T]
def wrap[T, E <: Exception](t: => T): Option[T] =
try Some(t) catch { case e: Exception => None }
def unwrap[Return](value: => Wrap[Return, _ <: Exception]): Return = value.get
override def toString = "[modes.returnOption]"
}
private[core] class ReturnFutureMode[+G <: MethodConstraint](implicit ec: ExecutionContext) extends Mode[G] {
type Wrap[+T, E <: Exception] = Future[T]
def wrap[T, E <: Exception](t: => T): Future[T] = Future { t }
def unwrap[Return](value: => Wrap[Return, _ <: Exception]): Return =
Await.result(value, duration.Duration.Inf)
override def flatWrap[Result, E <: Exception: ClassTag](blk: => Wrap[Result, E]): Wrap[Result, E] = blk
override def toString = "[modes.returnFuture]"
}
private[core] class TimeExecution[D: TimeSystem.ByDuration, +G <: MethodConstraint] extends Mode[G] {
val ts = ?[TimeSystem.ByDuration[D]]
type Wrap[+T, E <: Exception] = (T, D)
def wrap[T, E <: Exception](r: => T): (T, D) = {
val t0 = System.currentTimeMillis
(r, ts.duration(t0, System.currentTimeMillis))
}
def unwrap[Return](value: => Wrap[Return, _ <: Exception]): Return = value._1
override def toString = "[modes.timeExecution]"
}