/
TransactionInterceptionTest.java
320 lines (267 loc) · 11.8 KB
/
TransactionInterceptionTest.java
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance 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 org.apache.servicecomb.saga.omega.transaction.spring;
import static akka.actor.ActorRef.noSender;
import static com.seanyinx.github.unit.scaffolding.AssertUtils.expectFailing;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
import static java.util.Collections.singletonList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.servicecomb.saga.omega.transaction.spring.TransactionalUserService.ILLEGAL_USER;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.servicecomb.saga.omega.context.CompensationContext;
import org.apache.servicecomb.saga.omega.context.IdGenerator;
import org.apache.servicecomb.saga.omega.context.OmegaContext;
import org.apache.servicecomb.saga.omega.transaction.AlphaResponse;
import org.apache.servicecomb.saga.omega.transaction.MessageHandler;
import org.apache.servicecomb.saga.omega.transaction.MessageSender;
import org.apache.servicecomb.saga.omega.transaction.TxAbortedEvent;
import org.apache.servicecomb.saga.omega.transaction.TxCompensatedEvent;
import org.apache.servicecomb.saga.omega.transaction.TxEndedEvent;
import org.apache.servicecomb.saga.omega.transaction.TxStartedEvent;
import org.apache.servicecomb.saga.omega.transaction.spring.TransactionInterceptionTest.MessageConfig;
import org.apache.servicecomb.saga.omega.transaction.spring.annotations.OmegaContextAware;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;
import akka.actor.AbstractLoggingActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {TransactionTestMain.class, MessageConfig.class})
@AutoConfigureMockMvc
public class TransactionInterceptionTest {
@SuppressWarnings("unchecked")
private static final IdGenerator<String> idGenerator = Mockito.mock(IdGenerator.class);
private static final String globalTxId = UUID.randomUUID().toString();
private final String newLocalTxId = UUID.randomUUID().toString();
private final String anotherLocalTxId = UUID.randomUUID().toString();
private final String username = uniquify("username");
private final String email = uniquify("email");
private final User user = new User(username, email);
private final User illegalUser = new User(ILLEGAL_USER, email);
private final String usernameJack = uniquify("Jack");
private final User jack = new User(usernameJack, uniquify("jack@gmail.com"));
@OmegaContextAware
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
@Autowired
private List<String> messages;
@Autowired
private TransactionalUserService userService;
@Autowired
private OmegaContext omegaContext;
@Autowired
private UserRepository userRepository;
@Autowired
private MessageHandler messageHandler;
private String compensationMethod;
@Before
public void setUp() throws Exception {
when(idGenerator.nextId()).thenReturn(newLocalTxId, anotherLocalTxId);
omegaContext.setGlobalTxId(globalTxId);
omegaContext.setLocalTxId(globalTxId);
compensationMethod = TransactionalUserService.class.getDeclaredMethod("delete", User.class).toString();
}
@After
public void tearDown() throws Exception {
messages.clear();
userRepository.deleteAll();
omegaContext.clear();
}
@AfterClass
public static void afterClass() throws Exception {
}
@Test
public void sendsUserToRemote_AroundTransaction() throws Exception {
User user = userService.add(this.user);
assertArrayEquals(
new String[]{
new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod, 0, user).toString(),
new TxEndedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod).toString()},
toArray(messages)
);
User actual = userRepository.findByUsername(user.username());
assertThat(actual, is(user));
}
@Test
public void sendsAbortEvent_OnSubTransactionFailure() throws Exception {
Throwable throwable = null;
try {
userService.add(illegalUser);
expectFailing(IllegalArgumentException.class);
} catch (IllegalArgumentException ignored) {
throwable = ignored;
}
assertArrayEquals(
new String[]{
new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod, 0, illegalUser).toString(),
new TxAbortedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod, throwable).toString()},
toArray(messages)
);
}
@Test
public void compensateOnTransactionException() throws Exception {
User user = userService.add(this.user);
// another sub transaction to the same service within the same global transaction
String localTxId = omegaContext.newLocalTxId();
User anotherUser = userService.add(jack);
messageHandler.onReceive(globalTxId, newLocalTxId, globalTxId, compensationMethod, user);
messageHandler.onReceive(globalTxId, anotherLocalTxId, localTxId, compensationMethod, anotherUser);
assertThat(userRepository.findByUsername(user.username()), is(nullValue()));
assertThat(userRepository.findByUsername(anotherUser.username()), is(nullValue()));
assertArrayEquals(
new String[]{
new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod, 0, user).toString(),
new TxEndedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod).toString(),
new TxStartedEvent(globalTxId, anotherLocalTxId, localTxId, compensationMethod, 0, anotherUser).toString(),
new TxEndedEvent(globalTxId, anotherLocalTxId, localTxId, compensationMethod).toString(),
new TxCompensatedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod).toString(),
new TxCompensatedEvent(globalTxId, anotherLocalTxId, localTxId, compensationMethod).toString()
},
toArray(messages)
);
}
@Test
public void passesOmegaContextThroughDifferentThreads() throws Exception {
new Thread(() -> userService.add(user)).start();
waitTillSavedUser(username);
String localTxId = omegaContext.newLocalTxId();
new Thread(() -> userService.add(jack)).start();
waitTillSavedUser(usernameJack);
assertArrayEquals(
new String[]{
new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod, 0, user).toString(),
new TxEndedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod).toString(),
new TxStartedEvent(globalTxId, anotherLocalTxId, localTxId, compensationMethod, 0, jack).toString(),
new TxEndedEvent(globalTxId, anotherLocalTxId, localTxId, compensationMethod).toString()},
toArray(messages)
);
}
@Test
public void passesOmegaContextInThreadPool() throws Exception {
executor.schedule(() -> userService.add(user), 0, MILLISECONDS);
waitTillSavedUser(username);
String localTxId = omegaContext.newLocalTxId();
executor.invokeAll(singletonList(() -> userService.add(jack)));
waitTillSavedUser(usernameJack);
assertArrayEquals(
new String[]{
new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod, 0, user).toString(),
new TxEndedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod).toString(),
new TxStartedEvent(globalTxId, anotherLocalTxId, localTxId, compensationMethod, 0, jack).toString(),
new TxEndedEvent(globalTxId, anotherLocalTxId, localTxId, compensationMethod).toString()},
toArray(messages)
);
}
// TODO: 2018/1/4 reactive is not supported yet, omega context won't be updated on shared threads
@Test
public void passesOmegaContextThroughReactiveX() throws Exception {
Flowable.just(user)
.parallel()
.runOn(Schedulers.io())
.doOnNext(userService::add)
.sequential()
.subscribe();
waitTillSavedUser(username);
assertArrayEquals(
new String[]{
new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod, 0, user).toString(),
new TxEndedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod).toString()},
toArray(messages)
);
}
// TODO: 2018/1/4 actor system is not supported yet
@Test
public void passesOmegaContextAmongActors() throws Exception {
ActorSystem actorSystem = ActorSystem.create();
ActorRef actorRef = actorSystem.actorOf(UserServiceActor.props(userService));
actorRef.tell(user, noSender());
waitTillSavedUser(username);
assertArrayEquals(
new String[] {
new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod, 0, user).toString(),
new TxEndedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod).toString()},
toArray(messages)
);
actorSystem.terminate();
}
private void waitTillSavedUser(String username) {
await().atMost(1000, MILLISECONDS).until(() -> userRepository.findByUsername(username) != null);
}
private static class UserServiceActor extends AbstractLoggingActor {
private final TransactionalUserService userService;
private UserServiceActor(TransactionalUserService userService) {
this.userService = userService;
}
static Props props(TransactionalUserService userService) {
return Props.create(UserServiceActor.class, () -> new UserServiceActor(userService));
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(User.class, userService::add)
.build();
}
}
private String[] toArray(List<String> messages) {
return messages.toArray(new String[messages.size()]);
}
@Configuration
static class MessageConfig {
private final List<String> messages = new ArrayList<>();
@Bean
CompensationContext compensationContext() {
return new CompensationContext();
}
@Bean
OmegaContext omegaContext() {
return new OmegaContext(idGenerator);
}
@Bean
List<String> messages() {
return messages;
}
@Bean
MessageSender sender() {
return (event) -> {
messages.add(event.toString());
return new AlphaResponse(false);
};
}
}
}