You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@servicecomb.apache.org by GitBox <gi...@apache.org> on 2018/01/10 01:00:30 UTC

[GitHub] seanyinx closed pull request #109: [WIP]SCB-173 mark start of saga

seanyinx closed pull request #109: [WIP]SCB-173 mark start of saga
URL: https://github.com/apache/incubator-servicecomb-saga/pull/109
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/GreetingController.java b/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/GreetingController.java
index 12356ee0..3c7c0959 100644
--- a/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/GreetingController.java
+++ b/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/GreetingController.java
@@ -17,6 +17,7 @@
 
 package org.apache.servicecomb.saga.integration.pack.tests;
 
+import org.apache.servicecomb.saga.omega.context.annotations.SagaStart;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Controller;
@@ -38,7 +39,7 @@ public GreetingController(GreetingService greetingService, RestTemplate restTemp
     this.restTemplate = restTemplate;
   }
 
-
+  @SagaStart
   @GetMapping("/greet")
   ResponseEntity<String> greet(@RequestParam String name) {
     String greetings = greetingService.greet(name);
diff --git a/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/PackIT.java b/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/PackIT.java
index 66454b7d..32d42547 100644
--- a/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/PackIT.java
+++ b/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/PackIT.java
@@ -25,7 +25,6 @@
 import static org.hamcrest.Matchers.contains;
 import static org.hamcrest.core.Is.is;
 import static org.junit.Assert.assertThat;
-import static org.springframework.http.HttpMethod.GET;
 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
 import static org.springframework.http.HttpStatus.OK;
 
@@ -41,8 +40,6 @@
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
 import org.springframework.boot.test.web.client.TestRestTemplate;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
 import org.springframework.http.ResponseEntity;
 import org.springframework.test.context.junit4.SpringRunner;
 
@@ -72,90 +69,115 @@ public void tearDown() throws Exception {
 
   @Test
   public void updatesTxStateToAlpha() throws Exception {
-    HttpHeaders headers = new HttpHeaders();
-
-    headers.set(OmegaContext.GLOBAL_TX_ID_KEY, globalTxId);
-
-    ResponseEntity<String> entity = restTemplate.exchange("/greet?name={name}",
-        GET,
-        new HttpEntity<>(headers),
+    ResponseEntity<String> entity = restTemplate.getForEntity("/greet?name={name}",
         String.class,
         "mike");
 
     assertThat(entity.getStatusCode(), is(OK));
     assertThat(entity.getBody(), is("Greetings, mike; Bonjour, mike"));
 
-    List<TxEventEnvelope> envelopes = repository.findByGlobalTxIdOrderByCreationTime(globalTxId);
-
-    assertThat(envelopes.size(), is(4));
-    assertThat(envelopes.get(0).type(), is("TxStartedEvent"));
-    assertThat(envelopes.get(0).localTxId(), is(notNullValue()));
-    assertThat(envelopes.get(0).parentTxId(), is(nullValue()));
-    assertThat(envelopes.get(0).serviceName(), is(serviceName));
-    assertThat(envelopes.get(0).instanceId(), is(notNullValue()));
-
-    assertThat(envelopes.get(1).type(), is("TxEndedEvent"));
-    assertThat(envelopes.get(1).localTxId(), is(envelopes.get(0).localTxId()));
-    assertThat(envelopes.get(1).parentTxId(), is(nullValue()));
-    assertThat(envelopes.get(1).serviceName(), is(serviceName));
-    assertThat(envelopes.get(1).instanceId(), is(envelopes.get(0).instanceId()));
+    List<String> distinctGlobalTxIds = repository.findDistinctGlobalTxId();
+    assertThat(distinctGlobalTxIds.size(), is(1));
 
+    String globalTxId = distinctGlobalTxIds.get(0);
+    List<TxEventEnvelope> envelopes = repository.findByGlobalTxIdOrderByCreationTime(globalTxId);
 
-    assertThat(envelopes.get(2).type(), is("TxStartedEvent"));
-    assertThat(envelopes.get(2).localTxId(), is(notNullValue()));
-    assertThat(envelopes.get(2).parentTxId(), is(envelopes.get(0).localTxId()));
-    assertThat(envelopes.get(2).serviceName(), is(serviceName));
-    assertThat(envelopes.get(2).instanceId(), is(notNullValue()));
+    assertThat(envelopes.size(), is(6));
 
-    assertThat(envelopes.get(3).type(), is("TxEndedEvent"));
-    assertThat(envelopes.get(3).localTxId(), is(envelopes.get(2).localTxId()));
-    assertThat(envelopes.get(3).parentTxId(), is(envelopes.get(0).localTxId()));
-    assertThat(envelopes.get(3).serviceName(), is(serviceName));
-    assertThat(envelopes.get(3).instanceId(), is(envelopes.get(2).instanceId()));
+    TxEventEnvelope sagaStartedEventEnvelope = envelopes.get(0);
+    assertThat(sagaStartedEventEnvelope.type(), is("SagaStartedEvent"));
+    assertThat(sagaStartedEventEnvelope.localTxId(), is(notNullValue()));
+    assertThat(sagaStartedEventEnvelope.parentTxId(), is(nullValue()));
+    assertThat(sagaStartedEventEnvelope.serviceName(), is(serviceName));
+    assertThat(sagaStartedEventEnvelope.instanceId(), is(notNullValue()));
+
+    TxEventEnvelope txStartedEventEnvelope1 = envelopes.get(1);
+    assertThat(txStartedEventEnvelope1.type(), is("TxStartedEvent"));
+    assertThat(txStartedEventEnvelope1.localTxId(), is(notNullValue()));
+    assertThat(txStartedEventEnvelope1.parentTxId(), is(sagaStartedEventEnvelope.localTxId()));
+    assertThat(txStartedEventEnvelope1.serviceName(), is(serviceName));
+    assertThat(txStartedEventEnvelope1.instanceId(), is(sagaStartedEventEnvelope.instanceId()));
+
+    TxEventEnvelope txEndedEventEnvelope1 = envelopes.get(2);
+    assertThat(txEndedEventEnvelope1.type(), is("TxEndedEvent"));
+    assertThat(txEndedEventEnvelope1.localTxId(), is(txStartedEventEnvelope1.localTxId()));
+    assertThat(txEndedEventEnvelope1.parentTxId(), is(sagaStartedEventEnvelope.localTxId()));
+    assertThat(txEndedEventEnvelope1.serviceName(), is(serviceName));
+    assertThat(txEndedEventEnvelope1.instanceId(), is(txStartedEventEnvelope1.instanceId()));
+
+    TxEventEnvelope txStartedEventEnvelope2 = envelopes.get(3);
+    assertThat(txStartedEventEnvelope2.type(), is("TxStartedEvent"));
+    assertThat(txStartedEventEnvelope2.localTxId(), is(notNullValue()));
+    assertThat(txStartedEventEnvelope2.parentTxId(), is(txStartedEventEnvelope1.localTxId()));
+    assertThat(txStartedEventEnvelope2.serviceName(), is(serviceName));
+    assertThat(txStartedEventEnvelope2.instanceId(), is(notNullValue()));
+
+    TxEventEnvelope txEndedEventEnvelope2 = envelopes.get(4);
+    assertThat(txEndedEventEnvelope2.type(), is("TxEndedEvent"));
+    assertThat(txEndedEventEnvelope2.localTxId(), is(txStartedEventEnvelope2.localTxId()));
+    assertThat(txEndedEventEnvelope2.parentTxId(), is(txStartedEventEnvelope1.localTxId()));
+    assertThat(txEndedEventEnvelope2.serviceName(), is(serviceName));
+    assertThat(txEndedEventEnvelope2.instanceId(), is(txStartedEventEnvelope2.instanceId()));
+
+    TxEventEnvelope sagaEndedEventEnvelope = envelopes.get(5);
+    assertThat(sagaEndedEventEnvelope.type(), is("SagaEndedEvent"));
+    assertThat(sagaEndedEventEnvelope.localTxId(), is(sagaStartedEventEnvelope.localTxId()));
+    assertThat(sagaEndedEventEnvelope.parentTxId(), is(nullValue()));
+    assertThat(sagaEndedEventEnvelope.serviceName(), is(serviceName));
+    assertThat(sagaEndedEventEnvelope.instanceId(), is(notNullValue()));
 
     assertThat(compensatedMessages.isEmpty(), is(true));
   }
 
   @Test
   public void compensatesFailedGlobalTransaction() throws Exception {
-    HttpHeaders headers = new HttpHeaders();
-
-    headers.set(OmegaContext.GLOBAL_TX_ID_KEY, globalTxId);
-
-    ResponseEntity<String> entity = restTemplate.exchange("/greet?name={name}",
-        GET,
-        new HttpEntity<>(headers),
+    ResponseEntity<String> entity = restTemplate.getForEntity("/greet?name={name}",
         String.class,
         TRESPASSER);
 
     assertThat(entity.getStatusCode(), is(INTERNAL_SERVER_ERROR));
 
-    await().atMost(2, SECONDS).until(() -> repository.count() == 6);
+    await().atMost(2, SECONDS).until(() -> repository.count() == 8);
 
-    List<TxEventEnvelope> envelopes = repository.findByGlobalTxIdOrderByCreationTime(globalTxId);
-    assertThat(envelopes.size(), is(6));
+    List<String> distinctGlobalTxIds = repository.findDistinctGlobalTxId();
+    assertThat(distinctGlobalTxIds.size(), is(1));
 
-    assertThat(envelopes.get(0).type(), is("TxStartedEvent"));
-    assertThat(envelopes.get(1).type(), is("TxEndedEvent"));
-    assertThat(envelopes.get(2).type(), is("TxStartedEvent"));
-
-    assertThat(envelopes.get(3).type(), is("TxAbortedEvent"));
-    assertThat(envelopes.get(3).localTxId(), is(envelopes.get(2).localTxId()));
-    assertThat(envelopes.get(3).parentTxId(), is(envelopes.get(0).localTxId()));
-    assertThat(envelopes.get(3).serviceName(), is(serviceName));
-    assertThat(envelopes.get(3).instanceId(), is(envelopes.get(2).instanceId()));
-
-    assertThat(envelopes.get(4).type(), is("TxCompensatedEvent"));
-    assertThat(envelopes.get(4).localTxId(), is(envelopes.get(0).localTxId()));
-    assertThat(envelopes.get(4).parentTxId(), is(nullValue()));
-    assertThat(envelopes.get(4).serviceName(), is(serviceName));
-    assertThat(envelopes.get(4).instanceId(), is(envelopes.get(0).instanceId()));
-
-    assertThat(envelopes.get(5).type(), is("TxCompensatedEvent"));
-    assertThat(envelopes.get(5).localTxId(), is(envelopes.get(2).localTxId()));
-    assertThat(envelopes.get(5).parentTxId(), is(envelopes.get(0).localTxId()));
-    assertThat(envelopes.get(5).serviceName(), is(serviceName));
-    assertThat(envelopes.get(5).instanceId(), is(envelopes.get(2).instanceId()));
+    String globalTxId = distinctGlobalTxIds.get(0);
+    List<TxEventEnvelope> envelopes = repository.findByGlobalTxIdOrderByCreationTime(globalTxId);
+    assertThat(envelopes.size(), is(8));
+
+    TxEventEnvelope sagaStartedEventEnvelope = envelopes.get(0);
+    assertThat(sagaStartedEventEnvelope.type(), is("SagaStartedEvent"));
+
+    TxEventEnvelope txStartedEventEnvelope1 = envelopes.get(1);
+    assertThat(txStartedEventEnvelope1.type(), is("TxStartedEvent"));
+    assertThat(envelopes.get(2).type(), is("TxEndedEvent"));
+
+    TxEventEnvelope txStartedEventEnvelope2 = envelopes.get(3);
+    assertThat(txStartedEventEnvelope2.type(), is("TxStartedEvent"));
+
+    TxEventEnvelope txAbortedEventEnvelope = envelopes.get(4);
+    assertThat(txAbortedEventEnvelope.type(), is("TxAbortedEvent"));
+    assertThat(txAbortedEventEnvelope.localTxId(), is(txStartedEventEnvelope2.localTxId()));
+    assertThat(txAbortedEventEnvelope.parentTxId(), is(txStartedEventEnvelope1.localTxId()));
+    assertThat(txAbortedEventEnvelope.serviceName(), is(serviceName));
+    assertThat(txAbortedEventEnvelope.instanceId(), is(txStartedEventEnvelope2.instanceId()));
+
+    TxEventEnvelope txCompensatedEventEnvelope1 = envelopes.get(5);
+    assertThat(txCompensatedEventEnvelope1.type(), is("TxCompensatedEvent"));
+    assertThat(txCompensatedEventEnvelope1.localTxId(), is(txStartedEventEnvelope1.localTxId()));
+    assertThat(txCompensatedEventEnvelope1.parentTxId(), is(sagaStartedEventEnvelope.localTxId()));
+    assertThat(txCompensatedEventEnvelope1.serviceName(), is(serviceName));
+    assertThat(txCompensatedEventEnvelope1.instanceId(), is(txStartedEventEnvelope1.instanceId()));
+
+    TxEventEnvelope txCompensatedEventEnvelope2 = envelopes.get(6);
+    assertThat(txCompensatedEventEnvelope2.type(), is("TxCompensatedEvent"));
+    assertThat(txCompensatedEventEnvelope2.localTxId(), is(txStartedEventEnvelope2.localTxId()));
+    assertThat(txCompensatedEventEnvelope2.parentTxId(), is(txStartedEventEnvelope1.localTxId()));
+    assertThat(txCompensatedEventEnvelope2.serviceName(), is(serviceName));
+    assertThat(txCompensatedEventEnvelope2.instanceId(), is(txStartedEventEnvelope2.instanceId()));
+
+    assertThat(envelopes.get(7).type(), is("SagaEndedEvent"));
 
     assertThat(compensatedMessages, contains(
         "Goodbye, " + TRESPASSER,
diff --git a/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/TxEventEnvelope.java b/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/TxEventEnvelope.java
index d99c2b6a..0087dd71 100644
--- a/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/TxEventEnvelope.java
+++ b/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/TxEventEnvelope.java
@@ -50,6 +50,10 @@ String instanceId() {
     return instanceId;
   }
 
+  String globalTxId() {
+    return globalTxId;
+  }
+
   String localTxId() {
     return localTxId;
   }
diff --git a/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/TxEventEnvelopeRepository.java b/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/TxEventEnvelopeRepository.java
index 7e4b7e9c..5400d7cc 100644
--- a/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/TxEventEnvelopeRepository.java
+++ b/integration-tests/pack-tests/src/test/java/org/apache/servicecomb/saga/integration/pack/tests/TxEventEnvelopeRepository.java
@@ -19,8 +19,12 @@
 
 import java.util.List;
 
+import org.springframework.data.jpa.repository.Query;
 import org.springframework.data.repository.CrudRepository;
 
 interface TxEventEnvelopeRepository extends CrudRepository<TxEventEnvelope, Long> {
   List<TxEventEnvelope> findByGlobalTxIdOrderByCreationTime(String globalTxId);
+
+  @Query("SELECT DISTINCT(e.globalTxId) from TxEventEnvelope e")
+  List<String> findDistinctGlobalTxId();
 }
diff --git a/omega/omega-connector/omega-connector-grpc/src/main/java/org/apache/servicecomb/saga/omega/connector/grpc/GrpcClientMessageSender.java b/omega/omega-connector/omega-connector-grpc/src/main/java/org/apache/servicecomb/saga/omega/connector/grpc/GrpcClientMessageSender.java
index b2e837c2..59fbce18 100644
--- a/omega/omega-connector/omega-connector-grpc/src/main/java/org/apache/servicecomb/saga/omega/connector/grpc/GrpcClientMessageSender.java
+++ b/omega/omega-connector/omega-connector-grpc/src/main/java/org/apache/servicecomb/saga/omega/connector/grpc/GrpcClientMessageSender.java
@@ -84,13 +84,11 @@ private GrpcTxEvent convertEvent(TxEvent event) {
         .setTimestamp(event.timestamp())
         .setGlobalTxId(event.globalTxId())
         .setLocalTxId(event.localTxId())
+        .setParentTxId(event.parentTxId() == null ? "" : event.parentTxId())
         .setType(event.type())
         .setCompensationMethod(event.compensationMethod())
         .setPayloads(payloads);
 
-    if (event.parentTxId() != null) {
-      builder.setParentTxId(event.parentTxId());
-    }
     return builder.build();
   }
 
diff --git a/omega/omega-context/src/main/java/org/apache/servicecomb/saga/omega/context/annotations/SagaStart.java b/omega/omega-context/src/main/java/org/apache/servicecomb/saga/omega/context/annotations/SagaStart.java
new file mode 100644
index 00000000..435d72f3
--- /dev/null
+++ b/omega/omega-context/src/main/java/org/apache/servicecomb/saga/omega/context/annotations/SagaStart.java
@@ -0,0 +1,29 @@
+/*
+ * 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.context.annotations;
+
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Retention(RUNTIME)
+@Target(METHOD)
+public @interface SagaStart {
+}
diff --git a/omega/omega-spring-tx/src/main/java/org/apache/servicecomb/saga/omega/transaction/spring/CompensableMethodCheckingCallback.java b/omega/omega-spring-tx/src/main/java/org/apache/servicecomb/saga/omega/transaction/spring/CompensableMethodCheckingCallback.java
index 2793109e..ac6615cd 100644
--- a/omega/omega-spring-tx/src/main/java/org/apache/servicecomb/saga/omega/transaction/spring/CompensableMethodCheckingCallback.java
+++ b/omega/omega-spring-tx/src/main/java/org/apache/servicecomb/saga/omega/transaction/spring/CompensableMethodCheckingCallback.java
@@ -21,13 +21,12 @@
 import java.lang.reflect.Method;
 
 import org.apache.servicecomb.saga.omega.context.OmegaContext;
+import org.apache.servicecomb.saga.omega.transaction.OmegaException;
+import org.apache.servicecomb.saga.omega.transaction.annotations.Compensable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.util.ReflectionUtils.MethodCallback;
 
-import org.apache.servicecomb.saga.omega.transaction.OmegaException;
-import org.apache.servicecomb.saga.omega.transaction.annotations.Compensable;
-
 class CompensableMethodCheckingCallback implements MethodCallback {
   private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
@@ -40,7 +39,7 @@
   }
 
   @Override
-  public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
+  public void doWith(Method method) throws IllegalArgumentException {
     if (!method.isAnnotationPresent(Compensable.class)) {
       return;
     }
diff --git a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/SagaEndedEvent.java b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/SagaEndedEvent.java
new file mode 100644
index 00000000..3048d36d
--- /dev/null
+++ b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/SagaEndedEvent.java
@@ -0,0 +1,25 @@
+/*
+ * 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;
+
+public class SagaEndedEvent extends TxEvent {
+
+  public SagaEndedEvent(String globalTxId, String localTxId) {
+    super(globalTxId, localTxId, null, "");
+  }
+}
diff --git a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/SagaStartAnnotationProcessor.java b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/SagaStartAnnotationProcessor.java
new file mode 100644
index 00000000..e92ebb12
--- /dev/null
+++ b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/SagaStartAnnotationProcessor.java
@@ -0,0 +1,43 @@
+/*
+ * 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;
+
+import org.apache.servicecomb.saga.omega.context.OmegaContext;
+
+public class SagaStartAnnotationProcessor {
+
+  private final OmegaContext omegaContext;
+
+  private final MessageSender sender;
+
+  SagaStartAnnotationProcessor(OmegaContext omegaContext, MessageSender sender) {
+    this.omegaContext = omegaContext;
+    this.sender = sender;
+  }
+
+  void preIntercept() {
+    String globalTxId = omegaContext.newGlobalTxId();
+    // reuse the globalTxId as localTxId to differ localTxId in SagaStartedEvent and the first TxStartedEvent
+    sender.send(new SagaStartedEvent(globalTxId, globalTxId));
+  }
+
+  void postIntercept() {
+    String globalTxId = omegaContext.globalTxId();
+    sender.send(new SagaEndedEvent(globalTxId, globalTxId));
+  }
+}
diff --git a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/SagaStartedEvent.java b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/SagaStartedEvent.java
new file mode 100644
index 00000000..0985f595
--- /dev/null
+++ b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/SagaStartedEvent.java
@@ -0,0 +1,26 @@
+/*
+ * 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;
+
+public class SagaStartedEvent extends TxEvent {
+
+  public SagaStartedEvent(String globalTxId, String localTxId) {
+    // use "" instead of null as compensationMethod requires not null in sql
+    super(globalTxId, localTxId, null, "");
+  }
+}
diff --git a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspect.java b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspect.java
index 2b68da5b..bf13e3a0 100644
--- a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspect.java
+++ b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspect.java
@@ -20,6 +20,8 @@
 import java.lang.invoke.MethodHandles;
 import java.lang.reflect.Method;
 
+import org.apache.servicecomb.saga.omega.context.OmegaContext;
+import org.apache.servicecomb.saga.omega.transaction.annotations.Compensable;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
@@ -27,15 +29,14 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import org.apache.servicecomb.saga.omega.context.OmegaContext;
-import org.apache.servicecomb.saga.omega.transaction.annotations.Compensable;
-
 @Aspect
 public class TransactionAspect {
   private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
   private final PreTransactionInterceptor preTransactionInterceptor;
   private final PostTransactionInterceptor postTransactionInterceptor;
   private final FailedTransactionInterceptor failedTransactionInterceptor;
+
+  private final SagaStartAnnotationProcessor sagaStartAnnotationProcessor;
   private final OmegaContext context;
 
   public TransactionAspect(MessageSender sender, OmegaContext context) {
@@ -43,6 +44,7 @@ public TransactionAspect(MessageSender sender, OmegaContext context) {
     this.preTransactionInterceptor = new PreTransactionInterceptor(sender);
     this.postTransactionInterceptor = new PostTransactionInterceptor(sender);
     this.failedTransactionInterceptor = new FailedTransactionInterceptor(sender);
+    this.sagaStartAnnotationProcessor = new SagaStartAnnotationProcessor(this.context, sender);
   }
 
   @Around("execution(@org.apache.servicecomb.saga.omega.transaction.annotations.Compensable * *(..)) && @annotation(compensable)")
@@ -65,6 +67,24 @@ Object advise(ProceedingJoinPoint joinPoint, Compensable compensable) throws Thr
     }
   }
 
+  @Around("execution(@org.apache.servicecomb.saga.omega.context.annotations.SagaStart * *(..))")
+  Object advise(ProceedingJoinPoint joinPoint) throws Throwable {
+    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
+
+    LOG.debug("Initializing global tx id before execution of method {}", method.toString());
+    sagaStartAnnotationProcessor.preIntercept();
+
+    try {
+      return joinPoint.proceed();
+    } catch (Throwable throwable) {
+      LOG.error("Failed to process SagaStart method: {}", method.toString());
+      throw throwable;
+    } finally {
+      LOG.debug("Transaction {} has finished.", context.globalTxId());
+      sagaStartAnnotationProcessor.postIntercept();
+    }
+  }
+
   private String compensationMethodSignature(ProceedingJoinPoint joinPoint, Compensable compensable, Method method)
       throws NoSuchMethodException {
 
@@ -75,6 +95,9 @@ private String compensationMethodSignature(ProceedingJoinPoint joinPoint, Compen
   }
 
   private void preIntercept(ProceedingJoinPoint joinPoint, String signature) {
+    // context without a parent should be the first TxStartedEvent
+    initFirstOmegaContext();
+
     preTransactionInterceptor.intercept(
         context.globalTxId(),
         context.localTxId(),
@@ -99,4 +122,14 @@ private void interceptException(String signature, Throwable throwable) {
         signature,
         throwable);
   }
+
+  private void initFirstOmegaContext() {
+    if (context.parentTxId() != null) {
+      return;
+    }
+    if (context.localTxId() == null) {
+      context.newLocalTxId();
+    }
+    context.setParentTxId(context.globalTxId());
+  }
 }
diff --git a/omega/omega-transaction/src/test/java/org/apache/servicecomb/saga/omega/transaction/SagaStartAnnotationProcessorTest.java b/omega/omega-transaction/src/test/java/org/apache/servicecomb/saga/omega/transaction/SagaStartAnnotationProcessorTest.java
new file mode 100644
index 00000000..8913b7f6
--- /dev/null
+++ b/omega/omega-transaction/src/test/java/org/apache/servicecomb/saga/omega/transaction/SagaStartAnnotationProcessorTest.java
@@ -0,0 +1,89 @@
+/*
+ * 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;
+
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNull.nullValue;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import org.apache.servicecomb.saga.omega.context.IdGenerator;
+import org.apache.servicecomb.saga.omega.context.OmegaContext;
+import org.junit.Test;
+
+public class SagaStartAnnotationProcessorTest {
+
+  private final List<TxEvent> messages = new ArrayList<>();
+
+  private final MessageSender sender = messages::add;
+
+  private final String globalTxId = UUID.randomUUID().toString();
+
+  private final String localTxId = UUID.randomUUID().toString();
+
+  private final IdGenerator generator = mock(IdGenerator.class);
+
+  @SuppressWarnings("unchecked")
+  private final OmegaContext context = new OmegaContext(generator);
+
+  private final SagaStartAnnotationProcessor sagaStartAnnotationProcessor = new SagaStartAnnotationProcessor(context,
+      sender);
+
+  @Test
+  public void sendsSagaStartedEvent() {
+    when(generator.nextId()).thenReturn(globalTxId, localTxId);
+
+    sagaStartAnnotationProcessor.preIntercept();
+
+    assertThat(context.globalTxId(), is(globalTxId));
+    assertThat(context.localTxId(), is(nullValue()));
+    assertThat(context.parentTxId(), is(nullValue()));
+
+    TxEvent event = messages.get(0);
+
+    assertThat(event.globalTxId(), is(globalTxId));
+    assertThat(event.localTxId(), is(globalTxId));
+    assertThat(event.parentTxId(), is(nullValue()));
+    assertThat(event.compensationMethod().isEmpty(), is(true));
+    assertThat(event.type(), is("SagaStartedEvent"));
+    assertThat(event.payloads().length, is(0));
+  }
+
+  @Test
+  public void sendsSagaEndedEvent() {
+    context.clear();
+    context.setGlobalTxId(globalTxId);
+    context.setLocalTxId(localTxId);
+
+    sagaStartAnnotationProcessor.postIntercept();
+
+    TxEvent event = messages.get(0);
+
+    assertThat(event.globalTxId(), is(globalTxId));
+    assertThat(event.localTxId(), is(globalTxId));
+    assertThat(event.parentTxId(), is(nullValue()));
+    assertThat(event.compensationMethod().isEmpty(), is(true));
+    assertThat(event.type(), is("SagaEndedEvent"));
+    assertThat(event.payloads().length, is(0));
+  }
+}
\ No newline at end of file
diff --git a/omega/omega-transport/omega-transport-resttemplate/src/main/java/org/apache/servicecomb/saga/omega/transport/resttemplate/TransactionClientHttpRequestInterceptor.java b/omega/omega-transport/omega-transport-resttemplate/src/main/java/org/apache/servicecomb/saga/omega/transport/resttemplate/TransactionClientHttpRequestInterceptor.java
index 5b4ceda3..5e695980 100644
--- a/omega/omega-transport/omega-transport-resttemplate/src/main/java/org/apache/servicecomb/saga/omega/transport/resttemplate/TransactionClientHttpRequestInterceptor.java
+++ b/omega/omega-transport/omega-transport-resttemplate/src/main/java/org/apache/servicecomb/saga/omega/transport/resttemplate/TransactionClientHttpRequestInterceptor.java
@@ -38,26 +38,10 @@
   public ClientHttpResponse intercept(HttpRequest request, byte[] body,
       ClientHttpRequestExecution execution) throws IOException {
 
-    request.getHeaders().add(OmegaContext.GLOBAL_TX_ID_KEY, globalTxId());
-    request.getHeaders().add(OmegaContext.LOCAL_TX_ID_KEY, localTxId());
-    return execution.execute(request, body);
-  }
-
-  private String globalTxId() {
-    String globalTxId = omegaContext.globalTxId();
-
-    if (globalTxId == null) {
-      return omegaContext.newGlobalTxId();
+    if (omegaContext.globalTxId() != null) {
+      request.getHeaders().add(OmegaContext.GLOBAL_TX_ID_KEY, omegaContext.globalTxId());
+      request.getHeaders().add(OmegaContext.LOCAL_TX_ID_KEY, omegaContext.localTxId());
     }
-    return globalTxId;
-  }
-
-  private String localTxId() {
-    String localTxId = omegaContext.localTxId();
-
-    if (localTxId == null) {
-      return omegaContext.newLocalTxId();
-    }
-    return localTxId;
+    return execution.execute(request, body);
   }
 }
diff --git a/omega/omega-transport/omega-transport-resttemplate/src/test/java/org/apache/servicecomb/saga/omega/transport/resttemplate/TransactionClientHttpRequestInterceptorTest.java b/omega/omega-transport/omega-transport-resttemplate/src/test/java/org/apache/servicecomb/saga/omega/transport/resttemplate/TransactionClientHttpRequestInterceptorTest.java
index 82e74cf6..14e288e6 100644
--- a/omega/omega-transport/omega-transport-resttemplate/src/test/java/org/apache/servicecomb/saga/omega/transport/resttemplate/TransactionClientHttpRequestInterceptorTest.java
+++ b/omega/omega-transport/omega-transport-resttemplate/src/test/java/org/apache/servicecomb/saga/omega/transport/resttemplate/TransactionClientHttpRequestInterceptorTest.java
@@ -65,22 +65,18 @@ public void setUp() throws Exception {
   }
 
   @Test
-  public void newTransactionIdInHeaderIfNonExists() throws IOException {
+  public void keepHeaderUnchangedIfContextAbsent() throws IOException {
     when(request.getHeaders()).thenReturn(new HttpHeaders());
 
     when(execution.execute(request, null)).thenReturn(response);
 
     clientHttpRequestInterceptor.intercept(request, null, execution);
 
-    assertThat(request.getHeaders().get(OmegaContext.GLOBAL_TX_ID_KEY), contains(globalTxId));
-    assertThat(request.getHeaders().get(OmegaContext.LOCAL_TX_ID_KEY), contains(localTxId));
-
-    assertThat(omegaContext.globalTxId(), is(globalTxId));
-    assertThat(omegaContext.localTxId(), is(localTxId));
+    assertThat(request.getHeaders().isEmpty(), is(true));
   }
 
   @Test
-  public void sameTransactionIdInHeaderIfAlreadyExists() throws IOException {
+  public void interceptTransactionIdInHeaderIfContextPresent() throws IOException {
     omegaContext.setGlobalTxId(globalTxId);
     omegaContext.setLocalTxId(localTxId);
 
@@ -92,8 +88,5 @@ public void sameTransactionIdInHeaderIfAlreadyExists() throws IOException {
 
     assertThat(request.getHeaders().get(OmegaContext.GLOBAL_TX_ID_KEY), contains(globalTxId));
     assertThat(request.getHeaders().get(OmegaContext.LOCAL_TX_ID_KEY), contains(localTxId));
-
-    assertThat(omegaContext.globalTxId(), is(globalTxId));
-    assertThat(omegaContext.localTxId(), is(localTxId));
   }
 }


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services