allenwang37 commited on
Commit
cfc2173
·
verified ·
1 Parent(s): 4de3577

Publish Cloud-OpsBench v1.0.0 benchmark artifacts (part 18)

Browse files

Source: https://github.com/LLM4Ops/Cloud-OpsBench/tree/ea05dafbc87b5985df8721622d63d4229c2b4224

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. benchmark/boutique/codedefect/85/tool_cache.json +0 -0
  2. benchmark/boutique/codedefect/86/code/adservice/src/main/java/hipstershop/AdService.java +238 -0
  3. benchmark/boutique/codedefect/86/code/adservice/src/main/java/hipstershop/AdServiceClient.java +116 -0
  4. benchmark/boutique/codedefect/86/code/cartservice/src/Program.cs +26 -0
  5. benchmark/boutique/codedefect/86/code/cartservice/src/Startup.cs +84 -0
  6. benchmark/boutique/codedefect/86/code/cartservice/src/cartstore/AlloyDBCartStore.cs +177 -0
  7. benchmark/boutique/codedefect/86/code/cartservice/src/cartstore/ICartStore.cs +26 -0
  8. benchmark/boutique/codedefect/86/code/cartservice/src/cartstore/RedisCartStore.cs +118 -0
  9. benchmark/boutique/codedefect/86/code/cartservice/src/cartstore/SpannerCartStore.cs +185 -0
  10. benchmark/boutique/codedefect/86/code/cartservice/src/services/CartService.cs +51 -0
  11. benchmark/boutique/codedefect/86/code/cartservice/src/services/HealthCheckService.cs +41 -0
  12. benchmark/boutique/codedefect/86/code/checkoutservice/main.go +394 -0
  13. benchmark/boutique/codedefect/86/code/checkoutservice/money/money.go +132 -0
  14. benchmark/boutique/codedefect/86/code/currencyservice/client.js +68 -0
  15. benchmark/boutique/codedefect/86/code/currencyservice/server.js +198 -0
  16. benchmark/boutique/codedefect/86/code/emailservice/email_client.py +39 -0
  17. benchmark/boutique/codedefect/86/code/emailservice/email_server.py +200 -0
  18. benchmark/boutique/codedefect/86/code/emailservice/logger.py +41 -0
  19. benchmark/boutique/codedefect/86/code/frontend/deployment_details.go +64 -0
  20. benchmark/boutique/codedefect/86/code/frontend/handlers.go +635 -0
  21. benchmark/boutique/codedefect/86/code/frontend/main.go +235 -0
  22. benchmark/boutique/codedefect/86/code/frontend/middleware.go +111 -0
  23. benchmark/boutique/codedefect/86/code/frontend/money/money.go +132 -0
  24. benchmark/boutique/codedefect/86/code/frontend/packaging_info.go +79 -0
  25. benchmark/boutique/codedefect/86/code/frontend/rpc.go +127 -0
  26. benchmark/boutique/codedefect/86/code/frontend/validator/validator.go +83 -0
  27. benchmark/boutique/codedefect/86/code/paymentservice/charge.js +86 -0
  28. benchmark/boutique/codedefect/86/code/paymentservice/index.js +75 -0
  29. benchmark/boutique/codedefect/86/code/paymentservice/logger.js +27 -0
  30. benchmark/boutique/codedefect/86/code/paymentservice/server.js +106 -0
  31. benchmark/boutique/codedefect/86/code/productcatalogservice/catalog_loader.go +161 -0
  32. benchmark/boutique/codedefect/86/code/productcatalogservice/product_catalog.go +83 -0
  33. benchmark/boutique/codedefect/86/code/productcatalogservice/server.go +217 -0
  34. benchmark/boutique/codedefect/86/code/recommendationservice/client.py +39 -0
  35. benchmark/boutique/codedefect/86/code/recommendationservice/logger.py +41 -0
  36. benchmark/boutique/codedefect/86/code/recommendationservice/recommendation_server.py +156 -0
  37. benchmark/boutique/codedefect/86/code/shippingservice/main.go +183 -0
  38. benchmark/boutique/codedefect/86/code/shippingservice/quote.go +56 -0
  39. benchmark/boutique/codedefect/86/code/shippingservice/tracker.go +47 -0
  40. benchmark/boutique/codedefect/86/metadata.json +10 -0
  41. benchmark/boutique/codedefect/86/raw_data/alert.json +26 -0
  42. benchmark/boutique/codedefect/86/raw_data/k8s_states.json +0 -0
  43. benchmark/boutique/codedefect/86/raw_data/logs.json +0 -0
  44. benchmark/boutique/codedefect/86/raw_data/metrics.csv +54 -0
  45. benchmark/boutique/codedefect/86/tool_cache.json +0 -0
  46. benchmark/boutique/codedefect/87/code/adservice/src/main/java/hipstershop/AdService.java +238 -0
  47. benchmark/boutique/codedefect/87/code/adservice/src/main/java/hipstershop/AdServiceClient.java +116 -0
  48. benchmark/boutique/codedefect/87/code/cartservice/src/Program.cs +26 -0
  49. benchmark/boutique/codedefect/87/code/cartservice/src/Startup.cs +84 -0
  50. benchmark/boutique/codedefect/87/code/cartservice/src/cartstore/AlloyDBCartStore.cs +177 -0
benchmark/boutique/codedefect/85/tool_cache.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/boutique/codedefect/86/code/adservice/src/main/java/hipstershop/AdService.java ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2018, Google LLC.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ package hipstershop;
18
+
19
+ import com.google.common.collect.ImmutableListMultimap;
20
+ import com.google.common.collect.ImmutableMap;
21
+ import com.google.common.collect.Iterables;
22
+ import hipstershop.Demo.Ad;
23
+ import hipstershop.Demo.AdRequest;
24
+ import hipstershop.Demo.AdResponse;
25
+ import io.grpc.Server;
26
+ import io.grpc.ServerBuilder;
27
+ import io.grpc.StatusRuntimeException;
28
+ import io.grpc.health.v1.HealthCheckResponse.ServingStatus;
29
+ import io.grpc.services.*;
30
+ import io.grpc.stub.StreamObserver;
31
+ import java.io.IOException;
32
+ import java.util.ArrayList;
33
+ import java.util.Collection;
34
+ import java.util.List;
35
+ import java.util.Random;
36
+ import java.util.concurrent.TimeUnit;
37
+ import org.apache.logging.log4j.Level;
38
+ import org.apache.logging.log4j.LogManager;
39
+ import org.apache.logging.log4j.Logger;
40
+
41
+ public final class AdService {
42
+
43
+ private static final Logger logger = LogManager.getLogger(AdService.class);
44
+
45
+ @SuppressWarnings("FieldCanBeLocal")
46
+ private static int MAX_ADS_TO_SERVE = 2;
47
+
48
+ private Server server;
49
+ private HealthStatusManager healthMgr;
50
+
51
+ private static final AdService service = new AdService();
52
+
53
+ private void start() throws IOException {
54
+ int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "9555"));
55
+ healthMgr = new HealthStatusManager();
56
+
57
+ server =
58
+ ServerBuilder.forPort(port)
59
+ .addService(new AdServiceImpl())
60
+ .addService(healthMgr.getHealthService())
61
+ .build()
62
+ .start();
63
+ logger.info("Ad Service started, listening on " + port);
64
+ Runtime.getRuntime()
65
+ .addShutdownHook(
66
+ new Thread(
67
+ () -> {
68
+ // Use stderr here since the logger may have been reset by its JVM shutdown hook.
69
+ System.err.println(
70
+ "*** shutting down gRPC ads server since JVM is shutting down");
71
+ AdService.this.stop();
72
+ System.err.println("*** server shut down");
73
+ }));
74
+ healthMgr.setStatus("", ServingStatus.SERVING);
75
+ }
76
+
77
+ private void stop() {
78
+ if (server != null) {
79
+ healthMgr.clearStatus("");
80
+ server.shutdown();
81
+ }
82
+ }
83
+
84
+ private static class AdServiceImpl extends hipstershop.AdServiceGrpc.AdServiceImplBase {
85
+
86
+ /**
87
+ * Retrieves ads based on context provided in the request {@code AdRequest}.
88
+ *
89
+ * @param req the request containing context.
90
+ * @param responseObserver the stream observer which gets notified with the value of {@code
91
+ * AdResponse}
92
+ */
93
+ @Override
94
+ public void getAds(AdRequest req, StreamObserver<AdResponse> responseObserver) {
95
+ AdService service = AdService.getInstance();
96
+ try {
97
+ List<Ad> allAds = new ArrayList<>();
98
+ logger.info("received ad request (context_words=" + req.getContextKeysList() + ")");
99
+ if (req.getContextKeysCount() > 0) {
100
+ for (int i = 0; i < req.getContextKeysCount(); i++) {
101
+ Collection<Ad> ads = service.getAdsByCategory(req.getContextKeys(i));
102
+ allAds.addAll(ads);
103
+ }
104
+ } else {
105
+ allAds = service.getRandomAds();
106
+ }
107
+ if (allAds.isEmpty()) {
108
+ // Serve random ads.
109
+ allAds = service.getRandomAds();
110
+ }
111
+ AdResponse reply = AdResponse.newBuilder().addAllAds(allAds).build();
112
+ responseObserver.onNext(reply);
113
+ responseObserver.onCompleted();
114
+ } catch (StatusRuntimeException e) {
115
+ logger.log(Level.WARN, "GetAds Failed with status {}", e.getStatus());
116
+ responseObserver.onError(e);
117
+ }
118
+ }
119
+ }
120
+
121
+ private static final ImmutableListMultimap<String, Ad> adsMap = createAdsMap();
122
+
123
+ private Collection<Ad> getAdsByCategory(String category) {
124
+ return adsMap.get(category);
125
+ }
126
+
127
+ private static final Random random = new Random();
128
+
129
+ private List<Ad> getRandomAds() {
130
+ List<Ad> ads = new ArrayList<>(MAX_ADS_TO_SERVE);
131
+ Collection<Ad> allAds = adsMap.values();
132
+ for (int i = 0; i < MAX_ADS_TO_SERVE; i++) {
133
+ ads.add(Iterables.get(allAds, random.nextInt(allAds.size())));
134
+ }
135
+ return ads;
136
+ }
137
+
138
+ private static AdService getInstance() {
139
+ return service;
140
+ }
141
+
142
+ /** Await termination on the main thread since the grpc library uses daemon threads. */
143
+ private void blockUntilShutdown() throws InterruptedException {
144
+ if (server != null) {
145
+ server.awaitTermination();
146
+ }
147
+ }
148
+
149
+ private static ImmutableListMultimap<String, Ad> createAdsMap() {
150
+ Ad hairdryer =
151
+ Ad.newBuilder()
152
+ .setRedirectUrl("/product/2ZYFJ3GM2N")
153
+ .setText("Hairdryer for sale. 50% off.")
154
+ .build();
155
+ Ad tankTop =
156
+ Ad.newBuilder()
157
+ .setRedirectUrl("/product/66VCHSJNUP")
158
+ .setText("Tank top for sale. 20% off.")
159
+ .build();
160
+ Ad candleHolder =
161
+ Ad.newBuilder()
162
+ .setRedirectUrl("/product/0PUK6V6EV0")
163
+ .setText("Candle holder for sale. 30% off.")
164
+ .build();
165
+ Ad bambooGlassJar =
166
+ Ad.newBuilder()
167
+ .setRedirectUrl("/product/9SIQT8TOJO")
168
+ .setText("Bamboo glass jar for sale. 10% off.")
169
+ .build();
170
+ Ad watch =
171
+ Ad.newBuilder()
172
+ .setRedirectUrl("/product/1YMWWN1N4O")
173
+ .setText("Watch for sale. Buy one, get second kit for free")
174
+ .build();
175
+ Ad mug =
176
+ Ad.newBuilder()
177
+ .setRedirectUrl("/product/6E92ZMYYFZ")
178
+ .setText("Mug for sale. Buy two, get third one for free")
179
+ .build();
180
+ Ad loafers =
181
+ Ad.newBuilder()
182
+ .setRedirectUrl("/product/L9ECAV7KIM")
183
+ .setText("Loafers for sale. Buy one, get second one for free")
184
+ .build();
185
+ return ImmutableListMultimap.<String, Ad>builder()
186
+ .putAll("clothing", tankTop)
187
+ .putAll("accessories", watch)
188
+ .putAll("footwear", loafers)
189
+ .putAll("hair", hairdryer)
190
+ .putAll("decor", candleHolder)
191
+ .putAll("kitchen", bambooGlassJar, mug)
192
+ .build();
193
+ }
194
+
195
+ private static void initStats() {
196
+ if (System.getenv("DISABLE_STATS") != null) {
197
+ logger.info("Stats disabled.");
198
+ return;
199
+ }
200
+ logger.info("Stats enabled, but temporarily unavailable");
201
+
202
+ long sleepTime = 10; /* seconds */
203
+ int maxAttempts = 5;
204
+
205
+ // TODO(arbrown) Implement OpenTelemetry stats
206
+
207
+ }
208
+
209
+ private static void initTracing() {
210
+ if (System.getenv("DISABLE_TRACING") != null) {
211
+ logger.info("Tracing disabled.");
212
+ return;
213
+ }
214
+ logger.info("Tracing enabled but temporarily unavailable");
215
+ logger.info("See https://github.com/GoogleCloudPlatform/microservices-demo/issues/422 for more info.");
216
+
217
+ // TODO(arbrown) Implement OpenTelemetry tracing
218
+
219
+ logger.info("Tracing enabled - Stackdriver exporter initialized.");
220
+ }
221
+
222
+ /** Main launches the server from the command line. */
223
+ public static void main(String[] args) throws IOException, InterruptedException {
224
+
225
+ new Thread(
226
+ () -> {
227
+ initStats();
228
+ initTracing();
229
+ })
230
+ .start();
231
+
232
+ // Start the RPC server. You shouldn't see any output from gRPC before this.
233
+ logger.info("AdService starting.");
234
+ final AdService service = AdService.getInstance();
235
+ service.start();
236
+ service.blockUntilShutdown();
237
+ }
238
+ }
benchmark/boutique/codedefect/86/code/adservice/src/main/java/hipstershop/AdServiceClient.java ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2018, Google LLC.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ package hipstershop;
18
+
19
+ import hipstershop.Demo.Ad;
20
+ import hipstershop.Demo.AdRequest;
21
+ import hipstershop.Demo.AdResponse;
22
+ import io.grpc.ManagedChannel;
23
+ import io.grpc.ManagedChannelBuilder;
24
+ import io.grpc.StatusRuntimeException;
25
+ import java.util.concurrent.TimeUnit;
26
+ import javax.annotation.Nullable;
27
+ import org.apache.logging.log4j.Level;
28
+ import org.apache.logging.log4j.LogManager;
29
+ import org.apache.logging.log4j.Logger;
30
+
31
+ /** A simple client that requests ads from the Ads Service. */
32
+ public class AdServiceClient {
33
+
34
+ private static final Logger logger = LogManager.getLogger(AdServiceClient.class);
35
+
36
+ private final ManagedChannel channel;
37
+ private final hipstershop.AdServiceGrpc.AdServiceBlockingStub blockingStub;
38
+
39
+ /** Construct client connecting to Ad Service at {@code host:port}. */
40
+ private AdServiceClient(String host, int port) {
41
+ this(
42
+ ManagedChannelBuilder.forAddress(host, port)
43
+ // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
44
+ // needing certificates.
45
+ .usePlaintext()
46
+ .build());
47
+ }
48
+
49
+ /** Construct client for accessing RouteGuide server using the existing channel. */
50
+ private AdServiceClient(ManagedChannel channel) {
51
+ this.channel = channel;
52
+ blockingStub = hipstershop.AdServiceGrpc.newBlockingStub(channel);
53
+ }
54
+
55
+ private void shutdown() throws InterruptedException {
56
+ channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
57
+ }
58
+
59
+ /** Get Ads from Server. */
60
+ public void getAds(String contextKey) {
61
+ logger.info("Get Ads with context " + contextKey + " ...");
62
+ AdRequest request = AdRequest.newBuilder().addContextKeys(contextKey).build();
63
+ AdResponse response;
64
+
65
+ try {
66
+ response = blockingStub.getAds(request);
67
+ } catch (StatusRuntimeException e) {
68
+ logger.log(Level.WARN, "RPC failed: " + e.getStatus());
69
+ return;
70
+ }
71
+ for (Ad ads : response.getAdsList()) {
72
+ logger.info("Ads: " + ads.getText());
73
+ }
74
+ }
75
+
76
+ private static int getPortOrDefaultFromArgs(String[] args) {
77
+ int portNumber = 9555;
78
+ if (2 < args.length) {
79
+ try {
80
+ portNumber = Integer.parseInt(args[2]);
81
+ } catch (NumberFormatException e) {
82
+ logger.warn(String.format("Port %s is invalid, use default port %d.", args[2], 9555));
83
+ }
84
+ }
85
+ return portNumber;
86
+ }
87
+
88
+ private static String getStringOrDefaultFromArgs(
89
+ String[] args, int index, @Nullable String defaultString) {
90
+ String s = defaultString;
91
+ if (index < args.length) {
92
+ s = args[index];
93
+ }
94
+ return s;
95
+ }
96
+
97
+ /**
98
+ * Ads Service Client main. If provided, the first element of {@code args} is the context key to
99
+ * get the ads from the Ads Service
100
+ */
101
+ public static void main(String[] args) throws InterruptedException {
102
+ // Add final keyword to pass checkStyle.
103
+ final String contextKeys = getStringOrDefaultFromArgs(args, 0, "camera");
104
+ final String host = getStringOrDefaultFromArgs(args, 1, "localhost");
105
+ final int serverPort = getPortOrDefaultFromArgs(args);
106
+
107
+ AdServiceClient client = new AdServiceClient(host, serverPort);
108
+ try {
109
+ client.getAds(contextKeys);
110
+ } finally {
111
+ client.shutdown();
112
+ }
113
+
114
+ logger.info("Exiting AdServiceClient...");
115
+ }
116
+ }
benchmark/boutique/codedefect/86/code/cartservice/src/Program.cs ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using Microsoft.AspNetCore.Hosting;
16
+ using Microsoft.Extensions.Hosting;
17
+ using cartservice;
18
+
19
+ CreateHostBuilder(args).Build().Run();
20
+
21
+ static IHostBuilder CreateHostBuilder(string[] args) =>
22
+ Host.CreateDefaultBuilder(args)
23
+ .ConfigureWebHostDefaults(webBuilder =>
24
+ {
25
+ webBuilder.UseStartup<Startup>();
26
+ });
benchmark/boutique/codedefect/86/code/cartservice/src/Startup.cs ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+ using Microsoft.AspNetCore.Builder;
3
+ using Microsoft.AspNetCore.Diagnostics.HealthChecks;
4
+ using Microsoft.AspNetCore.Hosting;
5
+ using Microsoft.AspNetCore.Http;
6
+ using Microsoft.Extensions.Configuration;
7
+ using Microsoft.Extensions.DependencyInjection;
8
+ using Microsoft.Extensions.Diagnostics.HealthChecks;
9
+ using Microsoft.Extensions.Hosting;
10
+ using cartservice.cartstore;
11
+ using cartservice.services;
12
+ using Microsoft.Extensions.Caching.StackExchangeRedis;
13
+
14
+ namespace cartservice
15
+ {
16
+ public class Startup
17
+ {
18
+ public Startup(IConfiguration configuration)
19
+ {
20
+ Configuration = configuration;
21
+ }
22
+
23
+ public IConfiguration Configuration { get; }
24
+
25
+ // This method gets called by the runtime. Use this method to add services to the container.
26
+ // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
27
+ public void ConfigureServices(IServiceCollection services)
28
+ {
29
+ string redisAddress = Configuration["REDIS_ADDR"];
30
+ string spannerProjectId = Configuration["SPANNER_PROJECT"];
31
+ string spannerConnectionString = Configuration["SPANNER_CONNECTION_STRING"];
32
+ string alloyDBConnectionString = Configuration["ALLOYDB_PRIMARY_IP"];
33
+
34
+ if (!string.IsNullOrEmpty(redisAddress))
35
+ {
36
+ services.AddStackExchangeRedisCache(options =>
37
+ {
38
+ options.Configuration = redisAddress;
39
+ });
40
+ services.AddSingleton<ICartStore, RedisCartStore>();
41
+ }
42
+ else if (!string.IsNullOrEmpty(spannerProjectId) || !string.IsNullOrEmpty(spannerConnectionString))
43
+ {
44
+ services.AddSingleton<ICartStore, SpannerCartStore>();
45
+ }
46
+ else if (!string.IsNullOrEmpty(alloyDBConnectionString))
47
+ {
48
+ Console.WriteLine("Creating AlloyDB cart store");
49
+ services.AddSingleton<ICartStore, AlloyDBCartStore>();
50
+ }
51
+ else
52
+ {
53
+ Console.WriteLine("Redis cache host(hostname+port) was not specified. Starting a cart service using in memory store");
54
+ services.AddDistributedMemoryCache();
55
+ services.AddSingleton<ICartStore, RedisCartStore>();
56
+ }
57
+
58
+
59
+ services.AddGrpc();
60
+ }
61
+
62
+ // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
63
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
64
+ {
65
+ if (env.IsDevelopment())
66
+ {
67
+ app.UseDeveloperExceptionPage();
68
+ }
69
+
70
+ app.UseRouting();
71
+
72
+ app.UseEndpoints(endpoints =>
73
+ {
74
+ endpoints.MapGrpcService<CartService>();
75
+ endpoints.MapGrpcService<cartservice.services.HealthCheckService>();
76
+
77
+ endpoints.MapGet("/", async context =>
78
+ {
79
+ await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
80
+ });
81
+ });
82
+ }
83
+ }
84
+ }
benchmark/boutique/codedefect/86/code/cartservice/src/cartstore/AlloyDBCartStore.cs ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using Grpc.Core;
17
+ using Npgsql;
18
+ using Microsoft.Extensions.Configuration;
19
+ using System.Threading.Tasks;
20
+ using Google.Api.Gax.ResourceNames;
21
+ using Google.Cloud.SecretManager.V1;
22
+
23
+ namespace cartservice.cartstore
24
+ {
25
+ public class AlloyDBCartStore : ICartStore
26
+ {
27
+ private readonly string tableName;
28
+ private readonly string connectionString;
29
+
30
+ public AlloyDBCartStore(IConfiguration configuration)
31
+ {
32
+ // Create a Cloud Secrets client.
33
+ SecretManagerServiceClient client = SecretManagerServiceClient.Create();
34
+ var projectId = configuration["PROJECT_ID"];
35
+ var secretId = configuration["ALLOYDB_SECRET_NAME"];
36
+ SecretVersionName secretVersionName = new SecretVersionName(projectId, secretId, "latest");
37
+
38
+ AccessSecretVersionResponse result = client.AccessSecretVersion(secretVersionName);
39
+ // Convert the payload to a string. Payloads are bytes by default.
40
+ string alloyDBPassword = result.Payload.Data.ToStringUtf8().TrimEnd('\r', '\n');
41
+
42
+ // TODO: Create a separate user for connecting within the application
43
+ // rather than using our superuser
44
+ string alloyDBUser = "postgres";
45
+ string databaseName = configuration["ALLOYDB_DATABASE_NAME"];
46
+ // TODO: Consider splitting workloads into read vs. write and take
47
+ // advantage of the AlloyDB read pools
48
+ string primaryIPAddress = configuration["ALLOYDB_PRIMARY_IP"];
49
+ connectionString = "Host=" +
50
+ primaryIPAddress +
51
+ ";Username=" +
52
+ alloyDBUser +
53
+ ";Password=" +
54
+ alloyDBPassword +
55
+ ";Database=" +
56
+ databaseName;
57
+
58
+ tableName = configuration["ALLOYDB_TABLE_NAME"];
59
+ }
60
+
61
+
62
+ public async Task AddItemAsync(string userId, string productId, int quantity)
63
+ {
64
+ Console.WriteLine($"AddItemAsync for {userId} called");
65
+ try
66
+ {
67
+ await using var dataSource = NpgsqlDataSource.Create(connectionString);
68
+
69
+ var fetchCmd = $"SELECT quantity FROM {tableName} WHERE userID='{userId}' AND productID='{productId}'";
70
+ var currentQuantity = 0;
71
+ var cmdRead = dataSource.CreateCommand(fetchCmd);
72
+ await using (var reader = await cmdRead.ExecuteReaderAsync())
73
+ {
74
+ while (await reader.ReadAsync())
75
+ currentQuantity += reader.GetInt32(0);
76
+ }
77
+
78
+ var totalQuantity = quantity + currentQuantity;
79
+
80
+ // Use INSERT ... ON CONFLICT to prevent duplicate key error
81
+ var insertCmd = $@"
82
+ INSERT INTO {tableName} (userId, productId, quantity)
83
+ VALUES ('{userId}', '{productId}', {totalQuantity})
84
+ ON CONFLICT (userId, productId)
85
+ DO UPDATE SET quantity = {totalQuantity};
86
+ ";
87
+
88
+ await using (var cmdInsert = dataSource.CreateCommand(insertCmd))
89
+ {
90
+ await Task.Run(() =>
91
+ {
92
+ return cmdInsert.ExecuteNonQueryAsync();
93
+ });
94
+ }
95
+ }
96
+ catch (Exception ex)
97
+ {
98
+ throw new RpcException(
99
+ new Status(StatusCode.FailedPrecondition, $"Unable to access cart storage due to an internal error. {ex}"));
100
+ }
101
+ }
102
+
103
+
104
+ public async Task<Hipstershop.Cart> GetCartAsync(string userId)
105
+ {
106
+ Console.WriteLine($"GetCartAsync called for userId={userId}");
107
+ Hipstershop.Cart cart = new();
108
+ cart.UserId = userId;
109
+ try
110
+ {
111
+ await using var dataSource = NpgsqlDataSource.Create(connectionString);
112
+
113
+ var cartFetchCmd = $"SELECT productId, quantity FROM {tableName} WHERE userId = '{userId}'";
114
+ var cmd = dataSource.CreateCommand(cartFetchCmd);
115
+ await using (var reader = await cmd.ExecuteReaderAsync())
116
+ {
117
+ while (await reader.ReadAsync())
118
+ {
119
+ Hipstershop.CartItem item = new()
120
+ {
121
+ ProductId = reader.GetString(0),
122
+ Quantity = reader.GetInt32(1)
123
+ };
124
+ cart.Items.Add(item);
125
+ }
126
+ }
127
+ await Task.Run(() =>
128
+ {
129
+ return cart;
130
+ });
131
+ }
132
+ catch (Exception ex)
133
+ {
134
+ throw new RpcException(
135
+ new Status(StatusCode.FailedPrecondition, $"Unable to access cart storage due to an internal error. {ex}"));
136
+ }
137
+ return cart;
138
+ }
139
+
140
+
141
+ public async Task EmptyCartAsync(string userId)
142
+ {
143
+ Console.WriteLine($"EmptyCartAsync called for userId={userId}");
144
+
145
+ try
146
+ {
147
+ await using var dataSource = NpgsqlDataSource.Create(connectionString);
148
+ var deleteCmd = $"DELETE FROM {tableName} WHERE userID = '{userId}'";
149
+ await using (var cmd = dataSource.CreateCommand(deleteCmd))
150
+ {
151
+ await Task.Run(() =>
152
+ {
153
+ return cmd.ExecuteNonQueryAsync();
154
+ });
155
+ }
156
+ }
157
+ catch (Exception ex)
158
+ {
159
+ throw new RpcException(
160
+ new Status(StatusCode.FailedPrecondition, $"Unable to access cart storage due to an internal error. {ex}"));
161
+ }
162
+ }
163
+
164
+ public bool Ping()
165
+ {
166
+ try
167
+ {
168
+ return true;
169
+ }
170
+ catch (Exception)
171
+ {
172
+ return false;
173
+ }
174
+ }
175
+ }
176
+ }
177
+
benchmark/boutique/codedefect/86/code/cartservice/src/cartstore/ICartStore.cs ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System.Threading.Tasks;
16
+
17
+ namespace cartservice.cartstore
18
+ {
19
+ public interface ICartStore
20
+ {
21
+ Task AddItemAsync(string userId, string productId, int quantity);
22
+ Task EmptyCartAsync(string userId);
23
+ Task<Hipstershop.Cart> GetCartAsync(string userId);
24
+ bool Ping();
25
+ }
26
+ }
benchmark/boutique/codedefect/86/code/cartservice/src/cartstore/RedisCartStore.cs ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using System.Linq;
17
+ using System.Threading.Tasks;
18
+ using Grpc.Core;
19
+ using Microsoft.Extensions.Caching.Distributed;
20
+ using Google.Protobuf;
21
+
22
+ namespace cartservice.cartstore
23
+ {
24
+ public class RedisCartStore : ICartStore
25
+ {
26
+ private readonly IDistributedCache _cache;
27
+
28
+ public RedisCartStore(IDistributedCache cache)
29
+ {
30
+ _cache = cache;
31
+ }
32
+
33
+ public async Task AddItemAsync(string userId, string productId, int quantity)
34
+ {
35
+ Console.WriteLine($"AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}");
36
+
37
+ try
38
+ {
39
+ Hipstershop.Cart cart;
40
+ var value = await _cache.GetAsync(userId);
41
+ if (value == null)
42
+ {
43
+ cart = new Hipstershop.Cart();
44
+ cart.UserId = userId;
45
+ cart.Items.Add(new Hipstershop.CartItem { ProductId = productId, Quantity = quantity });
46
+ }
47
+ else
48
+ {
49
+ cart = Hipstershop.Cart.Parser.ParseFrom(value);
50
+ var existingItem = cart.Items.SingleOrDefault(i => i.ProductId == productId);
51
+ if (existingItem == null)
52
+ {
53
+ cart.Items.Add(new Hipstershop.CartItem { ProductId = productId, Quantity = quantity });
54
+ }
55
+ else
56
+ {
57
+ existingItem.Quantity += quantity;
58
+ }
59
+ }
60
+ await _cache.SetAsync(userId, cart.ToByteArray());
61
+ }
62
+ catch (Exception ex)
63
+ {
64
+ throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
65
+ }
66
+ }
67
+
68
+ public async Task EmptyCartAsync(string userId)
69
+ {
70
+ Console.WriteLine($"EmptyCartAsync called with userId={userId}");
71
+
72
+ try
73
+ {
74
+ var cart = new Hipstershop.Cart();
75
+ await _cache.SetAsync(userId, cart.ToByteArray());
76
+ }
77
+ catch (Exception ex)
78
+ {
79
+ throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
80
+ }
81
+ }
82
+
83
+ public async Task<Hipstershop.Cart> GetCartAsync(string userId)
84
+ {
85
+ Console.WriteLine($"GetCartAsync called with userId={userId}");
86
+
87
+ try
88
+ {
89
+ // Access the cart from the cache
90
+ var value = await _cache.GetAsync(userId);
91
+
92
+ if (value != null)
93
+ {
94
+ return Hipstershop.Cart.Parser.ParseFrom(value);
95
+ }
96
+
97
+ // We decided to return empty cart in cases when user wasn't in the cache before
98
+ return new Hipstershop.Cart();
99
+ }
100
+ catch (Exception ex)
101
+ {
102
+ throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
103
+ }
104
+ }
105
+
106
+ public bool Ping()
107
+ {
108
+ try
109
+ {
110
+ return true;
111
+ }
112
+ catch (Exception)
113
+ {
114
+ return false;
115
+ }
116
+ }
117
+ }
118
+ }
benchmark/boutique/codedefect/86/code/cartservice/src/cartstore/SpannerCartStore.cs ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using Google.Cloud.Spanner.Data;
17
+ using Grpc.Core;
18
+ using Microsoft.Extensions.Configuration;
19
+ using System.Threading.Tasks;
20
+
21
+ namespace cartservice.cartstore
22
+ {
23
+ public class SpannerCartStore : ICartStore
24
+ {
25
+ private static readonly string TableName = "CartItems";
26
+ private static readonly string DefaultInstanceName = "onlineboutique";
27
+ private static readonly string DefaultDatabaseName = "carts";
28
+ private readonly string databaseString;
29
+
30
+ public SpannerCartStore(IConfiguration configuration)
31
+ {
32
+ string spannerProjectId = configuration["SPANNER_PROJECT"];
33
+ string spannerInstanceId = configuration["SPANNER_INSTANCE"];
34
+ string spannerDatabaseId = configuration["SPANNER_DATABASE"];
35
+ string spannerConnectionString = configuration["SPANNER_CONNECTION_STRING"];
36
+ SpannerConnectionStringBuilder builder = new();
37
+ if (!string.IsNullOrEmpty(spannerConnectionString)) {
38
+ builder.DataSource = spannerConnectionString;
39
+ databaseString = builder.ToString();
40
+ Console.WriteLine($"Spanner connection string: ${databaseString}");
41
+ return;
42
+ }
43
+ if (string.IsNullOrEmpty(spannerInstanceId))
44
+ spannerInstanceId = DefaultInstanceName;
45
+ if (string.IsNullOrEmpty(spannerDatabaseId))
46
+ spannerDatabaseId = DefaultDatabaseName;
47
+ builder.DataSource =
48
+ $"projects/{spannerProjectId}/instances/{spannerInstanceId}/databases/{spannerDatabaseId}";
49
+ databaseString = builder.ToString();
50
+ Console.WriteLine($"Built Spanner connection string: '{databaseString}'");
51
+ }
52
+
53
+
54
+ public async Task AddItemAsync(string userId, string productId, int quantity)
55
+ {
56
+ Console.WriteLine($"AddItemAsync for {userId} called");
57
+ try
58
+ {
59
+ using SpannerConnection spannerConnection = new(databaseString);
60
+ await spannerConnection.RunWithRetriableTransactionAsync(async transaction =>
61
+ {
62
+ int currentQuantity = 0;
63
+ var quantityLookup = spannerConnection.CreateSelectCommand(
64
+ $"SELECT * FROM {TableName} WHERE userId = @userId AND productId = @productId",
65
+ new SpannerParameterCollection
66
+ {
67
+ { "userId", SpannerDbType.String },
68
+ { "productId", SpannerDbType.String }
69
+ });
70
+ quantityLookup.Parameters["userId"].Value = userId;
71
+ quantityLookup.Parameters["productId"].Value = productId;
72
+ quantityLookup.Transaction = transaction;
73
+ using (var reader = await quantityLookup.ExecuteReaderAsync())
74
+ {
75
+ while (await reader.ReadAsync()) {
76
+ currentQuantity += reader.GetFieldValue<int>("quantity");
77
+ }
78
+ }
79
+
80
+ var cmd = spannerConnection.CreateInsertOrUpdateCommand(TableName,
81
+ new SpannerParameterCollection
82
+ {
83
+ { "userId", SpannerDbType.String },
84
+ { "productId", SpannerDbType.String },
85
+ { "quantity", SpannerDbType.Int64 }
86
+ });
87
+ cmd.Parameters["userId"].Value = userId;
88
+ cmd.Parameters["productId"].Value = productId;
89
+ cmd.Parameters["quantity"].Value = currentQuantity + quantity;
90
+ cmd.Transaction = transaction;
91
+ await Task.Run(() =>
92
+ {
93
+ return cmd.ExecuteNonQueryAsync();
94
+ });
95
+ });
96
+ }
97
+ catch (Exception ex)
98
+ {
99
+ throw new RpcException(
100
+ new Status(StatusCode.FailedPrecondition, $"Can't access cart storage at {databaseString}. {ex}"));
101
+ }
102
+ }
103
+
104
+
105
+ public async Task<Hipstershop.Cart> GetCartAsync(string userId)
106
+ {
107
+ Console.WriteLine($"GetCartAsync called for userId={userId}");
108
+ Hipstershop.Cart cart = new();
109
+ try
110
+ {
111
+ using SpannerConnection spannerConnection = new(databaseString);
112
+ var cmd = spannerConnection.CreateSelectCommand(
113
+ $"SELECT * FROM {TableName} WHERE userId = @userId",
114
+ new SpannerParameterCollection {
115
+ { "userId", SpannerDbType.String }
116
+ }
117
+ );
118
+ cmd.Parameters["userId"].Value = userId;
119
+ using var reader = await cmd.ExecuteReaderAsync();
120
+ while (await reader.ReadAsync())
121
+ {
122
+ // Only add the userId if something is in the cart.
123
+ // This is based on how the cartservice example behaves.
124
+ // An empty cart has no userId attached.
125
+ cart.UserId = userId;
126
+
127
+ Hipstershop.CartItem item = new()
128
+ {
129
+ ProductId = reader.GetFieldValue<string>("productId"),
130
+ Quantity = reader.GetFieldValue<int>("quantity")
131
+ };
132
+ cart.Items.Add(item);
133
+ }
134
+
135
+ return cart;
136
+ }
137
+ catch (Exception ex)
138
+ {
139
+ throw new RpcException(
140
+ new Status(StatusCode.FailedPrecondition, $"Can't access cart storage at {databaseString}. {ex}"));
141
+ }
142
+ }
143
+
144
+
145
+ public async Task EmptyCartAsync(string userId)
146
+ {
147
+ Console.WriteLine($"EmptyCartAsync called for userId={userId}");
148
+
149
+ try
150
+ {
151
+ using SpannerConnection spannerConnection = new(databaseString);
152
+ await Task.Run(() =>
153
+ {
154
+ var cmd = spannerConnection.CreateDmlCommand(
155
+ $"DELETE FROM {TableName} WHERE userId = @userId",
156
+ new SpannerParameterCollection
157
+ {
158
+ { "userId", SpannerDbType.String }
159
+ });
160
+ cmd.Parameters["userId"].Value = userId;
161
+ return cmd.ExecuteNonQueryAsync();
162
+ });
163
+ }
164
+
165
+ catch (Exception ex)
166
+ {
167
+ throw new RpcException(
168
+ new Status(StatusCode.FailedPrecondition, $"Can't access cart storage at {databaseString}. {ex}"));
169
+ }
170
+ }
171
+
172
+ public bool Ping()
173
+ {
174
+ try
175
+ {
176
+ return true;
177
+ }
178
+ catch (Exception)
179
+ {
180
+ return false;
181
+ }
182
+ }
183
+ }
184
+ }
185
+
benchmark/boutique/codedefect/86/code/cartservice/src/services/CartService.cs ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using System.Threading.Tasks;
17
+ using Grpc.Core;
18
+ using Microsoft.Extensions.Logging;
19
+ using cartservice.cartstore;
20
+ using Hipstershop;
21
+
22
+ namespace cartservice.services
23
+ {
24
+ public class CartService : Hipstershop.CartService.CartServiceBase
25
+ {
26
+ private readonly static Empty Empty = new Empty();
27
+ private readonly ICartStore _cartStore;
28
+
29
+ public CartService(ICartStore cartStore)
30
+ {
31
+ _cartStore = cartStore;
32
+ }
33
+
34
+ public async override Task<Empty> AddItem(AddItemRequest request, ServerCallContext context)
35
+ {
36
+ await _cartStore.AddItemAsync(request.UserId, request.Item.ProductId, request.Item.Quantity);
37
+ return Empty;
38
+ }
39
+
40
+ public override Task<Cart> GetCart(GetCartRequest request, ServerCallContext context)
41
+ {
42
+ return _cartStore.GetCartAsync(request.UserId);
43
+ }
44
+
45
+ public async override Task<Empty> EmptyCart(EmptyCartRequest request, ServerCallContext context)
46
+ {
47
+ await _cartStore.EmptyCartAsync(request.UserId);
48
+ return Empty;
49
+ }
50
+ }
51
+ }
benchmark/boutique/codedefect/86/code/cartservice/src/services/HealthCheckService.cs ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using System.Threading.Tasks;
17
+ using Grpc.Core;
18
+ using Grpc.Health.V1;
19
+ using static Grpc.Health.V1.Health;
20
+ using cartservice.cartstore;
21
+
22
+ namespace cartservice.services
23
+ {
24
+ internal class HealthCheckService : HealthBase
25
+ {
26
+ private ICartStore _cartStore { get; }
27
+
28
+ public HealthCheckService (ICartStore cartStore)
29
+ {
30
+ _cartStore = cartStore;
31
+ }
32
+
33
+ public override Task<HealthCheckResponse> Check(HealthCheckRequest request, ServerCallContext context)
34
+ {
35
+ Console.WriteLine ("Checking CartService Health");
36
+ return Task.FromResult(new HealthCheckResponse {
37
+ Status = _cartStore.Ping() ? HealthCheckResponse.Types.ServingStatus.Serving : HealthCheckResponse.Types.ServingStatus.NotServing
38
+ });
39
+ }
40
+ }
41
+ }
benchmark/boutique/codedefect/86/code/checkoutservice/main.go ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "fmt"
20
+ "net"
21
+ "os"
22
+ "time"
23
+
24
+ "cloud.google.com/go/profiler"
25
+ "github.com/google/uuid"
26
+ "github.com/pkg/errors"
27
+ "github.com/sirupsen/logrus"
28
+ "google.golang.org/grpc"
29
+ "google.golang.org/grpc/codes"
30
+ "google.golang.org/grpc/credentials/insecure"
31
+ "google.golang.org/grpc/health"
32
+ "google.golang.org/grpc/status"
33
+
34
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/checkoutservice/genproto"
35
+ money "github.com/GoogleCloudPlatform/microservices-demo/src/checkoutservice/money"
36
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
37
+
38
+ "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
39
+ "go.opentelemetry.io/otel"
40
+ "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
41
+ "go.opentelemetry.io/otel/propagation"
42
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
43
+ )
44
+
45
+ const (
46
+ listenPort = "5050"
47
+ usdCurrency = "USD"
48
+ )
49
+
50
+ var log *logrus.Logger
51
+
52
+ func init() {
53
+ log = logrus.New()
54
+ log.Level = logrus.DebugLevel
55
+ log.Formatter = &logrus.JSONFormatter{
56
+ FieldMap: logrus.FieldMap{
57
+ logrus.FieldKeyTime: "timestamp",
58
+ logrus.FieldKeyLevel: "severity",
59
+ logrus.FieldKeyMsg: "message",
60
+ },
61
+ TimestampFormat: time.RFC3339Nano,
62
+ }
63
+ log.Out = os.Stdout
64
+ }
65
+
66
+ type checkoutService struct {
67
+ pb.UnimplementedCheckoutServiceServer
68
+
69
+ productCatalogSvcAddr string
70
+ productCatalogSvcConn *grpc.ClientConn
71
+
72
+ cartSvcAddr string
73
+ cartSvcConn *grpc.ClientConn
74
+
75
+ currencySvcAddr string
76
+ currencySvcConn *grpc.ClientConn
77
+
78
+ shippingSvcAddr string
79
+ shippingSvcConn *grpc.ClientConn
80
+
81
+ emailSvcAddr string
82
+ emailSvcConn *grpc.ClientConn
83
+
84
+ paymentSvcAddr string
85
+ paymentSvcConn *grpc.ClientConn
86
+ }
87
+
88
+ func main() {
89
+ ctx := context.Background()
90
+ if os.Getenv("ENABLE_TRACING") == "1" {
91
+ log.Info("Tracing enabled.")
92
+ initTracing()
93
+
94
+ } else {
95
+ log.Info("Tracing disabled.")
96
+ }
97
+
98
+ if os.Getenv("ENABLE_PROFILER") == "1" {
99
+ log.Info("Profiling enabled.")
100
+ go initProfiling("checkoutservice", "1.0.0")
101
+ } else {
102
+ log.Info("Profiling disabled.")
103
+ }
104
+
105
+ port := listenPort
106
+ if os.Getenv("PORT") != "" {
107
+ port = os.Getenv("PORT")
108
+ }
109
+
110
+ svc := new(checkoutService)
111
+ mustMapEnv(&svc.shippingSvcAddr, "SHIPPING_SERVICE_ADDR")
112
+ mustMapEnv(&svc.productCatalogSvcAddr, "PRODUCT_CATALOG_SERVICE_ADDR")
113
+ mustMapEnv(&svc.cartSvcAddr, "CART_SERVICE_ADDR")
114
+ mustMapEnv(&svc.currencySvcAddr, "CURRENCY_SERVICE_ADDR")
115
+ mustMapEnv(&svc.emailSvcAddr, "EMAIL_SERVICE_ADDR")
116
+ mustMapEnv(&svc.paymentSvcAddr, "PAYMENT_SERVICE_ADDR")
117
+
118
+ mustConnGRPC(ctx, &svc.shippingSvcConn, svc.shippingSvcAddr)
119
+ mustConnGRPC(ctx, &svc.productCatalogSvcConn, svc.productCatalogSvcAddr)
120
+ mustConnGRPC(ctx, &svc.cartSvcConn, svc.cartSvcAddr)
121
+ mustConnGRPC(ctx, &svc.currencySvcConn, svc.currencySvcAddr)
122
+ mustConnGRPC(ctx, &svc.emailSvcConn, svc.emailSvcAddr)
123
+ mustConnGRPC(ctx, &svc.paymentSvcConn, svc.paymentSvcAddr)
124
+
125
+ log.Infof("service config: %+v", svc)
126
+
127
+ lis, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
128
+ if err != nil {
129
+ log.Fatal(err)
130
+ }
131
+
132
+ var srv *grpc.Server
133
+
134
+ // Propagate trace context always
135
+ otel.SetTextMapPropagator(
136
+ propagation.NewCompositeTextMapPropagator(
137
+ propagation.TraceContext{}, propagation.Baggage{}))
138
+ srv = grpc.NewServer(
139
+ grpc.StatsHandler(otelgrpc.NewServerHandler()),
140
+ )
141
+
142
+ pb.RegisterCheckoutServiceServer(srv, svc)
143
+ healthcheck := health.NewServer()
144
+ healthpb.RegisterHealthServer(srv, healthcheck)
145
+ log.Infof("starting to listen on tcp: %q", lis.Addr().String())
146
+ err = srv.Serve(lis)
147
+ log.Fatal(err)
148
+ }
149
+
150
+ func initStats() {
151
+ //TODO(arbrown) Implement OpenTelemetry stats
152
+ }
153
+
154
+ func initTracing() {
155
+ var (
156
+ collectorAddr string
157
+ collectorConn *grpc.ClientConn
158
+ )
159
+
160
+ ctx := context.Background()
161
+ ctx, cancel := context.WithTimeout(ctx, time.Second*3)
162
+ defer cancel()
163
+
164
+ mustMapEnv(&collectorAddr, "COLLECTOR_SERVICE_ADDR")
165
+ mustConnGRPC(ctx, &collectorConn, collectorAddr)
166
+
167
+ exporter, err := otlptracegrpc.New(
168
+ ctx,
169
+ otlptracegrpc.WithGRPCConn(collectorConn))
170
+ if err != nil {
171
+ log.Warnf("warn: Failed to create trace exporter: %v", err)
172
+ }
173
+ tp := sdktrace.NewTracerProvider(
174
+ sdktrace.WithBatcher(exporter),
175
+ sdktrace.WithSampler(sdktrace.AlwaysSample()))
176
+ otel.SetTracerProvider(tp)
177
+
178
+ }
179
+
180
+ func initProfiling(service, version string) {
181
+ // TODO(ahmetb) this method is duplicated in other microservices using Go
182
+ // since they are not sharing packages.
183
+ for i := 1; i <= 3; i++ {
184
+ if err := profiler.Start(profiler.Config{
185
+ Service: service,
186
+ ServiceVersion: version,
187
+ // ProjectID must be set if not running on GCP.
188
+ // ProjectID: "my-project",
189
+ }); err != nil {
190
+ log.Warnf("failed to start profiler: %+v", err)
191
+ } else {
192
+ log.Info("started Stackdriver profiler")
193
+ return
194
+ }
195
+ d := time.Second * 10 * time.Duration(i)
196
+ log.Infof("sleeping %v to retry initializing Stackdriver profiler", d)
197
+ time.Sleep(d)
198
+ }
199
+ log.Warn("could not initialize Stackdriver profiler after retrying, giving up")
200
+ }
201
+
202
+ func mustMapEnv(target *string, envKey string) {
203
+ v := os.Getenv(envKey)
204
+ if v == "" {
205
+ panic(fmt.Sprintf("environment variable %q not set", envKey))
206
+ }
207
+ *target = v
208
+ }
209
+
210
+ func mustConnGRPC(ctx context.Context, conn **grpc.ClientConn, addr string) {
211
+ var err error
212
+ _, cancel := context.WithTimeout(ctx, time.Second*3)
213
+ defer cancel()
214
+ *conn, err = grpc.NewClient(addr,
215
+ grpc.WithTransportCredentials(insecure.NewCredentials()),
216
+ grpc.WithStatsHandler(otelgrpc.NewClientHandler()))
217
+ if err != nil {
218
+ panic(errors.Wrapf(err, "grpc: failed to connect %s", addr))
219
+ }
220
+ }
221
+
222
+ func (cs *checkoutService) Check(ctx context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
223
+ return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
224
+ }
225
+
226
+ func (cs *checkoutService) Watch(req *healthpb.HealthCheckRequest, ws healthpb.Health_WatchServer) error {
227
+ return status.Errorf(codes.Unimplemented, "health check via Watch not implemented")
228
+ }
229
+
230
+ func (cs *checkoutService) PlaceOrder(ctx context.Context, req *pb.PlaceOrderRequest) (*pb.PlaceOrderResponse, error) {
231
+ log.Infof("[PlaceOrder] user_id=%q user_currency=%q", req.UserId, req.UserCurrency)
232
+
233
+ orderID, err := uuid.NewUUID()
234
+ if err != nil {
235
+ return nil, status.Errorf(codes.Internal, "failed to generate order uuid")
236
+ }
237
+
238
+ prep, err := cs.prepareOrderItemsAndShippingQuoteFromCart(ctx, req.UserId, req.UserCurrency, req.Address)
239
+ if err != nil {
240
+ return nil, status.Errorf(codes.Internal, err.Error())
241
+ }
242
+
243
+ total := pb.Money{CurrencyCode: req.UserCurrency,
244
+ Units: 0,
245
+ Nanos: 0}
246
+ total = money.Must(money.Sum(total, *prep.shippingCostLocalized))
247
+ for _, it := range prep.orderItems {
248
+ multPrice := money.MultiplySlow(*it.Cost, uint32(it.GetItem().GetQuantity()))
249
+ total = money.Must(money.Sum(total, multPrice))
250
+ }
251
+
252
+ txID, err := cs.chargeCard(ctx, &total, req.CreditCard)
253
+ if err != nil {
254
+ return nil, status.Errorf(codes.Internal, "failed to charge card: %+v", err)
255
+ }
256
+ log.Infof("payment went through (transaction_id: %s)", txID)
257
+
258
+ shippingTrackingID, err := cs.shipOrder(ctx, req.Address, prep.cartItems)
259
+ if err != nil {
260
+ return nil, status.Errorf(codes.Unavailable, "shipping error: %+v", err)
261
+ }
262
+
263
+ _ = cs.emptyUserCart(ctx, req.UserId)
264
+
265
+ orderResult := &pb.OrderResult{
266
+ OrderId: orderID.String(),
267
+ ShippingTrackingId: shippingTrackingID,
268
+ ShippingCost: prep.shippingCostLocalized,
269
+ ShippingAddress: req.Address,
270
+ Items: prep.orderItems,
271
+ }
272
+
273
+ if err := cs.sendOrderConfirmation(ctx, req.Email, orderResult); err != nil {
274
+ log.Warnf("failed to send order confirmation to %q: %+v", req.Email, err)
275
+ } else {
276
+ log.Infof("order confirmation email sent to %q", req.Email)
277
+ }
278
+ resp := &pb.PlaceOrderResponse{Order: orderResult}
279
+ return resp, nil
280
+ }
281
+
282
+ type orderPrep struct {
283
+ orderItems []*pb.OrderItem
284
+ cartItems []*pb.CartItem
285
+ shippingCostLocalized *pb.Money
286
+ }
287
+
288
+ func (cs *checkoutService) prepareOrderItemsAndShippingQuoteFromCart(ctx context.Context, userID, userCurrency string, address *pb.Address) (orderPrep, error) {
289
+ var out orderPrep
290
+ cartItems, err := cs.getUserCart(ctx, userID)
291
+ if err != nil {
292
+ return out, fmt.Errorf("cart failure: %+v", err)
293
+ }
294
+ orderItems, err := cs.prepOrderItems(ctx, cartItems, userCurrency)
295
+ if err != nil {
296
+ return out, fmt.Errorf("failed to prepare order: %+v", err)
297
+ }
298
+ shippingUSD, err := cs.quoteShipping(ctx, address, cartItems)
299
+ if err != nil {
300
+ return out, fmt.Errorf("shipping quote failure: %+v", err)
301
+ }
302
+ shippingPrice, err := cs.convertCurrency(ctx, shippingUSD, userCurrency)
303
+ if err != nil {
304
+ return out, fmt.Errorf("failed to convert shipping cost to currency: %+v", err)
305
+ }
306
+
307
+ out.shippingCostLocalized = shippingPrice
308
+ out.cartItems = cartItems
309
+ out.orderItems = orderItems
310
+ return out, nil
311
+ }
312
+
313
+ func (cs *checkoutService) quoteShipping(ctx context.Context, address *pb.Address, items []*pb.CartItem) (*pb.Money, error) {
314
+ shippingQuote, err := pb.NewShippingServiceClient(cs.shippingSvcConn).
315
+ GetQuote(ctx, &pb.GetQuoteRequest{
316
+ Address: address,
317
+ Items: items})
318
+ if err != nil {
319
+ return nil, fmt.Errorf("failed to get shipping quote: %+v", err)
320
+ }
321
+ return shippingQuote.GetCostUsd(), nil
322
+ }
323
+
324
+ func (cs *checkoutService) getUserCart(ctx context.Context, userID string) ([]*pb.CartItem, error) {
325
+ cart, err := pb.NewCartServiceClient(cs.cartSvcConn).GetCart(ctx, &pb.GetCartRequest{UserId: userID})
326
+ if err != nil {
327
+ return nil, fmt.Errorf("failed to get user cart during checkout: %+v", err)
328
+ }
329
+ return cart.GetItems(), nil
330
+ }
331
+
332
+ func (cs *checkoutService) emptyUserCart(ctx context.Context, userID string) error {
333
+ if _, err := pb.NewCartServiceClient(cs.cartSvcConn).EmptyCart(ctx, &pb.EmptyCartRequest{UserId: userID}); err != nil {
334
+ return fmt.Errorf("failed to empty user cart during checkout: %+v", err)
335
+ }
336
+ return nil
337
+ }
338
+
339
+ func (cs *checkoutService) prepOrderItems(ctx context.Context, items []*pb.CartItem, userCurrency string) ([]*pb.OrderItem, error) {
340
+ out := make([]*pb.OrderItem, len(items))
341
+ cl := pb.NewProductCatalogServiceClient(cs.productCatalogSvcConn)
342
+
343
+ for i, item := range items {
344
+ product, err := cl.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()})
345
+ if err != nil {
346
+ return nil, fmt.Errorf("failed to get product #%q", item.GetProductId())
347
+ }
348
+ price, err := cs.convertCurrency(ctx, product.GetPriceUsd(), userCurrency)
349
+ if err != nil {
350
+ return nil, fmt.Errorf("failed to convert price of %q to %s", item.GetProductId(), userCurrency)
351
+ }
352
+ out[i] = &pb.OrderItem{
353
+ Item: item,
354
+ Cost: price}
355
+ }
356
+ return out, nil
357
+ }
358
+
359
+ func (cs *checkoutService) convertCurrency(ctx context.Context, from *pb.Money, toCurrency string) (*pb.Money, error) {
360
+ result, err := pb.NewCurrencyServiceClient(cs.currencySvcConn).Convert(context.TODO(), &pb.CurrencyConversionRequest{
361
+ From: from,
362
+ ToCode: toCurrency})
363
+ if err != nil {
364
+ return nil, fmt.Errorf("failed to convert currency: %+v", err)
365
+ }
366
+ return result, err
367
+ }
368
+
369
+ func (cs *checkoutService) chargeCard(ctx context.Context, amount *pb.Money, paymentInfo *pb.CreditCardInfo) (string, error) {
370
+ paymentResp, err := pb.NewPaymentServiceClient(cs.paymentSvcConn).Charge(ctx, &pb.ChargeRequest{
371
+ Amount: amount,
372
+ CreditCard: paymentInfo})
373
+ if err != nil {
374
+ return "", fmt.Errorf("could not charge the card: %+v", err)
375
+ }
376
+ return paymentResp.GetTransactionId(), nil
377
+ }
378
+
379
+ func (cs *checkoutService) sendOrderConfirmation(ctx context.Context, email string, order *pb.OrderResult) error {
380
+ _, err := pb.NewEmailServiceClient(cs.emailSvcConn).SendOrderConfirmation(ctx, &pb.SendOrderConfirmationRequest{
381
+ Email: email,
382
+ Order: order})
383
+ return err
384
+ }
385
+
386
+ func (cs *checkoutService) shipOrder(ctx context.Context, address *pb.Address, items []*pb.CartItem) (string, error) {
387
+ resp, err := pb.NewShippingServiceClient(cs.shippingSvcConn).ShipOrder(ctx, &pb.ShipOrderRequest{
388
+ Address: address,
389
+ Items: items})
390
+ if err != nil {
391
+ return "", fmt.Errorf("shipment failed: %+v", err)
392
+ }
393
+ return resp.GetTrackingId(), nil
394
+ }
benchmark/boutique/codedefect/86/code/checkoutservice/money/money.go ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package money
16
+
17
+ import (
18
+ "errors"
19
+
20
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/checkoutservice/genproto"
21
+ )
22
+
23
+ const (
24
+ nanosMin = -999999999
25
+ nanosMax = +999999999
26
+ nanosMod = 1000000000
27
+ )
28
+
29
+ var (
30
+ ErrInvalidValue = errors.New("one of the specified money values is invalid")
31
+ ErrMismatchingCurrency = errors.New("mismatching currency codes")
32
+ )
33
+
34
+ // IsValid checks if specified value has a valid units/nanos signs and ranges.
35
+ func IsValid(m pb.Money) bool {
36
+ return signMatches(m) && validNanos(m.GetNanos())
37
+ }
38
+
39
+ func signMatches(m pb.Money) bool {
40
+ return m.GetNanos() == 0 || m.GetUnits() == 0 || (m.GetNanos() < 0) == (m.GetUnits() < 0)
41
+ }
42
+
43
+ func validNanos(nanos int32) bool { return nanosMin <= nanos && nanos <= nanosMax }
44
+
45
+ // IsZero returns true if the specified money value is equal to zero.
46
+ func IsZero(m pb.Money) bool { return m.GetUnits() == 0 && m.GetNanos() == 0 }
47
+
48
+ // IsPositive returns true if the specified money value is valid and is
49
+ // positive.
50
+ func IsPositive(m pb.Money) bool {
51
+ return IsValid(m) && m.GetUnits() > 0 || (m.GetUnits() == 0 && m.GetNanos() > 0)
52
+ }
53
+
54
+ // IsNegative returns true if the specified money value is valid and is
55
+ // negative.
56
+ func IsNegative(m pb.Money) bool {
57
+ return IsValid(m) && m.GetUnits() < 0 || (m.GetUnits() == 0 && m.GetNanos() < 0)
58
+ }
59
+
60
+ // AreSameCurrency returns true if values l and r have a currency code and
61
+ // they are the same values.
62
+ func AreSameCurrency(l, r pb.Money) bool {
63
+ return l.GetCurrencyCode() == r.GetCurrencyCode() && l.GetCurrencyCode() != ""
64
+ }
65
+
66
+ // AreEquals returns true if values l and r are the equal, including the
67
+ // currency. This does not check validity of the provided values.
68
+ func AreEquals(l, r pb.Money) bool {
69
+ return l.GetCurrencyCode() == r.GetCurrencyCode() &&
70
+ l.GetUnits() == r.GetUnits() && l.GetNanos() == r.GetNanos()
71
+ }
72
+
73
+ // Negate returns the same amount with the sign negated.
74
+ func Negate(m pb.Money) pb.Money {
75
+ return pb.Money{
76
+ Units: -m.GetUnits(),
77
+ Nanos: -m.GetNanos(),
78
+ CurrencyCode: m.GetCurrencyCode()}
79
+ }
80
+
81
+ // Must panics if the given error is not nil. This can be used with other
82
+ // functions like: "m := Must(Sum(a,b))".
83
+ func Must(v pb.Money, err error) pb.Money {
84
+ if err != nil {
85
+ panic(err)
86
+ }
87
+ return v
88
+ }
89
+
90
+ // Sum adds two values. Returns an error if one of the values are invalid or
91
+ // currency codes are not matching (unless currency code is unspecified for
92
+ // both).
93
+ func Sum(l, r pb.Money) (pb.Money, error) {
94
+ if !IsValid(l) || !IsValid(r) {
95
+ return pb.Money{}, ErrInvalidValue
96
+ } else if l.GetCurrencyCode() != r.GetCurrencyCode() {
97
+ return pb.Money{}, ErrMismatchingCurrency
98
+ }
99
+ units := l.GetUnits() + r.GetUnits()
100
+ nanos := l.GetNanos() + r.GetNanos()
101
+
102
+ if (units == 0 && nanos == 0) || (units > 0 && nanos >= 0) || (units < 0 && nanos <= 0) {
103
+ // same sign <units, nanos>
104
+ units += int64(nanos / nanosMod)
105
+ nanos = nanos % nanosMod
106
+ } else {
107
+ // different sign. nanos guaranteed to not to go over the limit
108
+ if units > 0 {
109
+ units--
110
+ nanos += nanosMod
111
+ } else {
112
+ units++
113
+ nanos -= nanosMod
114
+ }
115
+ }
116
+
117
+ return pb.Money{
118
+ Units: units,
119
+ Nanos: nanos,
120
+ CurrencyCode: l.GetCurrencyCode()}, nil
121
+ }
122
+
123
+ // MultiplySlow is a slow multiplication operation done through adding the value
124
+ // to itself n-1 times.
125
+ func MultiplySlow(m pb.Money, n uint32) pb.Money {
126
+ out := m
127
+ for n > 1 {
128
+ out = Must(Sum(out, m))
129
+ n--
130
+ }
131
+ return out
132
+ }
benchmark/boutique/codedefect/86/code/currencyservice/client.js ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ *
3
+ * Copyright 2015 gRPC authors.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ *
17
+ */
18
+ require('@google-cloud/trace-agent').start();
19
+
20
+ const path = require('path');
21
+ const grpc = require('grpc');
22
+ const pino = require('pino');
23
+
24
+ const PROTO_PATH = path.join(__dirname, './proto/demo.proto');
25
+ const PORT = 7000;
26
+
27
+ const shopProto = grpc.load(PROTO_PATH).hipstershop;
28
+ const client = new shopProto.CurrencyService(`localhost:${PORT}`,
29
+ grpc.credentials.createInsecure());
30
+
31
+ const logger = pino({
32
+ name: 'currencyservice-client',
33
+ messageKey: 'message',
34
+ formatters: {
35
+ level (logLevelString, logLevelNum) {
36
+ return { severity: logLevelString }
37
+ }
38
+ }
39
+ });
40
+
41
+ const request = {
42
+ from: {
43
+ currency_code: 'CHF',
44
+ units: 300,
45
+ nanos: 0
46
+ },
47
+ to_code: 'EUR'
48
+ };
49
+
50
+ function _moneyToString (m) {
51
+ return `${m.units}.${m.nanos.toString().padStart(9,'0')} ${m.currency_code}`;
52
+ }
53
+
54
+ client.getSupportedCurrencies({}, (err, response) => {
55
+ if (err) {
56
+ logger.error(`Error in getSupportedCurrencies: ${err}`);
57
+ } else {
58
+ logger.info(`Currency codes: ${response.currency_codes}`);
59
+ }
60
+ });
61
+
62
+ client.convert(request, (err, response) => {
63
+ if (err) {
64
+ logger.error(`Error in convert: ${err}`);
65
+ } else {
66
+ logger.log(`Convert: ${_moneyToString(request.from)} to ${_moneyToString(response)}`);
67
+ }
68
+ });
benchmark/boutique/codedefect/86/code/currencyservice/server.js ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2018 Google LLC.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ const pino = require('pino');
18
+ const logger = pino({
19
+ name: 'currencyservice-server',
20
+ messageKey: 'message',
21
+ formatters: {
22
+ level (logLevelString, logLevelNum) {
23
+ return { severity: logLevelString }
24
+ }
25
+ }
26
+ });
27
+
28
+ if(process.env.DISABLE_PROFILER) {
29
+ logger.info("Profiler disabled.")
30
+ }
31
+ else {
32
+ logger.info("Profiler enabled.")
33
+ require('@google-cloud/profiler').start({
34
+ serviceContext: {
35
+ service: 'currencyservice',
36
+ version: '1.0.0'
37
+ }
38
+ });
39
+ }
40
+
41
+ // Register GRPC OTel Instrumentation for trace propagation
42
+ // regardless of whether tracing is emitted.
43
+ const { GrpcInstrumentation } = require('@opentelemetry/instrumentation-grpc');
44
+ const { registerInstrumentations } = require('@opentelemetry/instrumentation');
45
+
46
+ registerInstrumentations({
47
+ instrumentations: [new GrpcInstrumentation()]
48
+ });
49
+
50
+ if(process.env.ENABLE_TRACING == "1") {
51
+ logger.info("Tracing enabled.")
52
+
53
+ const { resourceFromAttributes } = require('@opentelemetry/resources');
54
+
55
+ const { ATTR_SERVICE_NAME } = require('@opentelemetry/semantic-conventions');
56
+
57
+ const opentelemetry = require('@opentelemetry/sdk-node');
58
+
59
+ const { OTLPTraceExporter } = require('@opentelemetry/exporter-otlp-grpc');
60
+
61
+ const collectorUrl = process.env.COLLECTOR_SERVICE_ADDR;
62
+ const traceExporter = new OTLPTraceExporter({url: collectorUrl});
63
+ const sdk = new opentelemetry.NodeSDK({
64
+ resource: resourceFromAttributes({
65
+ [ ATTR_SERVICE_NAME ]: process.env.OTEL_SERVICE_NAME || 'currencyservice',
66
+ }),
67
+ traceExporter: traceExporter,
68
+ });
69
+
70
+ sdk.start()
71
+ }
72
+ else {
73
+ logger.info("Tracing disabled.")
74
+ }
75
+
76
+ const path = require('path');
77
+ const grpc = require('@grpc/grpc-js');
78
+ const protoLoader = require('@grpc/proto-loader');
79
+
80
+ const MAIN_PROTO_PATH = path.join(__dirname, './proto/demo.proto');
81
+ const HEALTH_PROTO_PATH = path.join(__dirname, './proto/grpc/health/v1/health.proto');
82
+
83
+ const PORT = process.env.PORT;
84
+
85
+ const shopProto = _loadProto(MAIN_PROTO_PATH).hipstershop;
86
+ const healthProto = _loadProto(HEALTH_PROTO_PATH).grpc.health.v1;
87
+
88
+ /**
89
+ * Helper function that loads a protobuf file.
90
+ */
91
+ function _loadProto (path) {
92
+ const packageDefinition = protoLoader.loadSync(
93
+ path,
94
+ {
95
+ keepCase: true,
96
+ longs: String,
97
+ enums: String,
98
+ defaults: true,
99
+ oneofs: true
100
+ }
101
+ );
102
+ return grpc.loadPackageDefinition(packageDefinition);
103
+ }
104
+
105
+ /**
106
+ * Helper function that gets currency data from a stored JSON file
107
+ * Uses public data from European Central Bank
108
+ */
109
+ function _getCurrencyData (callback) {
110
+ const data = require('./data/currency_conversion.json');
111
+ callback(data);
112
+ }
113
+
114
+ /**
115
+ * Helper function that handles decimal/fractional carrying
116
+ */
117
+ function _carry (amount) {
118
+ const fractionSize = Math.pow(10, 9);
119
+ amount.nanos += (amount.units % 1) * fractionSize;
120
+ amount.units = Math.floor(amount.units) + Math.floor(amount.nanos / fractionSize);
121
+ amount.nanos = amount.nanos % fractionSize;
122
+ return amount;
123
+ }
124
+
125
+ /**
126
+ * Lists the supported currencies
127
+ */
128
+ function getSupportedCurrencies (call, callback) {
129
+ logger.info('Getting supported currencies...');
130
+ _getCurrencyData((data) => {
131
+ callback(null, {currency_codes: Object.keys(data)});
132
+ });
133
+ }
134
+
135
+ /**
136
+ * Converts between currencies
137
+ */
138
+ function convert (call, callback) {
139
+ try {
140
+ _getCurrencyData((data) => {
141
+ const request = call.request;
142
+
143
+ // Convert: from_currency --> EUR
144
+ const from = request.from;
145
+ const euros = _carry({
146
+ units: from.units / data[from.currency_code],
147
+ nanos: from.nanos / data[from.currency_code]
148
+ });
149
+
150
+ euros.nanos = Math.round(euros.nanos);
151
+
152
+ // Convert: EUR --> to_currency
153
+ const result = _carry({
154
+ units: euros.units * data[request.to_code],
155
+ nanos: euros.nanos * data[request.to_code]
156
+ });
157
+
158
+ result.units = Math.floor(result.units);
159
+ result.nanos = Math.floor(result.nanos);
160
+ result.currency_code = request.to_code;
161
+
162
+ logger.info(`conversion request successful`);
163
+ callback(null, result);
164
+ });
165
+ } catch (err) {
166
+ logger.error(`conversion request failed: ${err}`);
167
+ callback(err.message);
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Endpoint for health checks
173
+ */
174
+ function check (call, callback) {
175
+ callback(null, { status: 'SERVING' });
176
+ }
177
+
178
+ /**
179
+ * Starts an RPC server that receives requests for the
180
+ * CurrencyConverter service at the sample server port
181
+ */
182
+ function main () {
183
+ logger.info(`Starting gRPC server on port ${PORT}...`);
184
+ const server = new grpc.Server();
185
+ server.addService(shopProto.CurrencyService.service, {getSupportedCurrencies, convert});
186
+ server.addService(healthProto.Health.service, {check});
187
+
188
+ server.bindAsync(
189
+ `[::]:${PORT}`,
190
+ grpc.ServerCredentials.createInsecure(),
191
+ function() {
192
+ logger.info(`CurrencyService gRPC server started on port ${PORT}`);
193
+ server.start();
194
+ },
195
+ );
196
+ }
197
+
198
+ main();
benchmark/boutique/codedefect/86/code/emailservice/email_client.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import grpc
18
+
19
+ import demo_pb2
20
+ import demo_pb2_grpc
21
+
22
+ from logger import getJSONLogger
23
+ logger = getJSONLogger('emailservice-client')
24
+
25
+ def send_confirmation_email(email, order):
26
+ channel = grpc.insecure_channel('[::]:8080')
27
+ stub = demo_pb2_grpc.EmailServiceStub(channel)
28
+ try:
29
+ response = stub.SendOrderConfirmation(demo_pb2.SendOrderConfirmationRequest(
30
+ email = email,
31
+ order = order
32
+ ))
33
+ logger.info('Request sent.')
34
+ except grpc.RpcError as err:
35
+ logger.error(err.details())
36
+ logger.error('{}, {}'.format(err.code().name, err.code().value))
37
+
38
+ if __name__ == '__main__':
39
+ logger.info('Client for email service.')
benchmark/boutique/codedefect/86/code/emailservice/email_server.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from concurrent import futures
18
+ import argparse
19
+ import os
20
+ import sys
21
+ import time
22
+ import grpc
23
+ import traceback
24
+ from jinja2 import Environment, FileSystemLoader, select_autoescape, TemplateError
25
+ from google.api_core.exceptions import GoogleAPICallError
26
+ from google.auth.exceptions import DefaultCredentialsError
27
+
28
+ import demo_pb2
29
+ import demo_pb2_grpc
30
+ from grpc_health.v1 import health_pb2
31
+ from grpc_health.v1 import health_pb2_grpc
32
+
33
+ from opentelemetry import trace
34
+ from opentelemetry.instrumentation.grpc import GrpcInstrumentorServer
35
+ from opentelemetry.sdk.trace import TracerProvider
36
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
37
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
38
+
39
+ # @TODO: Temporarily removed in https://github.com/GoogleCloudPlatform/microservices-demo/pull/3196
40
+ # import googlecloudprofiler
41
+
42
+ from logger import getJSONLogger
43
+ logger = getJSONLogger('emailservice-server')
44
+
45
+ # Loads confirmation email template from file
46
+ env = Environment(
47
+ loader=FileSystemLoader('templates'),
48
+ autoescape=select_autoescape(['html', 'xml'])
49
+ )
50
+ template = env.get_template('confirmation.html')
51
+
52
+ class BaseEmailService(demo_pb2_grpc.EmailServiceServicer):
53
+ def Check(self, request, context):
54
+ return health_pb2.HealthCheckResponse(
55
+ status=health_pb2.HealthCheckResponse.SERVING)
56
+
57
+ def Watch(self, request, context):
58
+ return health_pb2.HealthCheckResponse(
59
+ status=health_pb2.HealthCheckResponse.UNIMPLEMENTED)
60
+
61
+ class EmailService(BaseEmailService):
62
+ def __init__(self):
63
+ raise Exception('cloud mail client not implemented')
64
+ super().__init__()
65
+
66
+ @staticmethod
67
+ def send_email(client, email_address, content):
68
+ response = client.send_message(
69
+ sender = client.sender_path(project_id, region, sender_id),
70
+ envelope_from_authority = '',
71
+ header_from_authority = '',
72
+ envelope_from_address = from_address,
73
+ simple_message = {
74
+ "from": {
75
+ "address_spec": from_address,
76
+ },
77
+ "to": [{
78
+ "address_spec": email_address
79
+ }],
80
+ "subject": "Your Confirmation Email",
81
+ "html_body": content
82
+ }
83
+ )
84
+ logger.info("Message sent: {}".format(response.rfc822_message_id))
85
+
86
+ def SendOrderConfirmation(self, request, context):
87
+ email = request.email
88
+ order = request.order
89
+
90
+ try:
91
+ confirmation = template.render(order = order)
92
+ except TemplateError as err:
93
+ context.set_details("An error occurred when preparing the confirmation mail.")
94
+ logger.error(err.message)
95
+ context.set_code(grpc.StatusCode.INTERNAL)
96
+ return demo_pb2.Empty()
97
+
98
+ try:
99
+ EmailService.send_email(self.client, email, confirmation)
100
+ except GoogleAPICallError as err:
101
+ context.set_details("An error occurred when sending the email.")
102
+ print(err.message)
103
+ context.set_code(grpc.StatusCode.INTERNAL)
104
+ return demo_pb2.Empty()
105
+
106
+ return demo_pb2.Empty()
107
+
108
+ class DummyEmailService(BaseEmailService):
109
+ def SendOrderConfirmation(self, request, context):
110
+ logger.info('A request to send order confirmation email to {} has been received.'.format(request.email))
111
+ return demo_pb2.Empty()
112
+
113
+ class HealthCheck():
114
+ def Check(self, request, context):
115
+ return health_pb2.HealthCheckResponse(
116
+ status=health_pb2.HealthCheckResponse.SERVING)
117
+
118
+ def start(dummy_mode):
119
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),)
120
+ service = None
121
+ if dummy_mode:
122
+ service = DummyEmailService()
123
+ else:
124
+ raise Exception('non-dummy mode not implemented yet')
125
+
126
+ demo_pb2_grpc.add_EmailServiceServicer_to_server(service, server)
127
+ health_pb2_grpc.add_HealthServicer_to_server(service, server)
128
+
129
+ port = os.environ.get('PORT', "8080")
130
+ logger.info("listening on port: "+port)
131
+ server.add_insecure_port('[::]:'+port)
132
+ server.start()
133
+ try:
134
+ while True:
135
+ time.sleep(3600)
136
+ except KeyboardInterrupt:
137
+ server.stop(0)
138
+
139
+ def initStackdriverProfiling():
140
+ project_id = None
141
+ try:
142
+ project_id = os.environ["GCP_PROJECT_ID"]
143
+ except KeyError:
144
+ # Environment variable not set
145
+ pass
146
+
147
+ # @TODO: Temporarily removed in https://github.com/GoogleCloudPlatform/microservices-demo/pull/3196
148
+ # for retry in range(1,4):
149
+ # try:
150
+ # if project_id:
151
+ # googlecloudprofiler.start(service='email_server', service_version='1.0.0', verbose=0, project_id=project_id)
152
+ # else:
153
+ # googlecloudprofiler.start(service='email_server', service_version='1.0.0', verbose=0)
154
+ # logger.info("Successfully started Stackdriver Profiler.")
155
+ # return
156
+ # except (BaseException) as exc:
157
+ # logger.info("Unable to start Stackdriver Profiler Python agent. " + str(exc))
158
+ # if (retry < 4):
159
+ # logger.info("Sleeping %d to retry initializing Stackdriver Profiler"%(retry*10))
160
+ # time.sleep (1)
161
+ # else:
162
+ # logger.warning("Could not initialize Stackdriver Profiler after retrying, giving up")
163
+ return
164
+
165
+
166
+ if __name__ == '__main__':
167
+ logger.info('starting the email service in dummy mode.')
168
+
169
+ # Profiler
170
+ try:
171
+ if "DISABLE_PROFILER" in os.environ:
172
+ raise KeyError()
173
+ else:
174
+ logger.info("Profiler enabled.")
175
+ initStackdriverProfiling()
176
+ except KeyError:
177
+ logger.info("Profiler disabled.")
178
+
179
+ # Tracing
180
+ try:
181
+ if os.environ["ENABLE_TRACING"] == "1":
182
+ otel_endpoint = os.getenv("COLLECTOR_SERVICE_ADDR", "localhost:4317")
183
+ trace.set_tracer_provider(TracerProvider())
184
+ trace.get_tracer_provider().add_span_processor(
185
+ BatchSpanProcessor(
186
+ OTLPSpanExporter(
187
+ endpoint = otel_endpoint,
188
+ insecure = True
189
+ )
190
+ )
191
+ )
192
+ grpc_server_instrumentor = GrpcInstrumentorServer()
193
+ grpc_server_instrumentor.instrument()
194
+
195
+ except (KeyError, DefaultCredentialsError):
196
+ logger.info("Tracing disabled.")
197
+ except Exception as e:
198
+ logger.warn(f"Exception on Cloud Trace setup: {traceback.format_exc()}, tracing disabled.")
199
+
200
+ start(dummy_mode = True)
benchmark/boutique/codedefect/86/code/emailservice/logger.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import logging
18
+ import sys
19
+ from pythonjsonlogger import jsonlogger
20
+
21
+ # TODO(yoshifumi) this class is duplicated since other Python services are
22
+ # not sharing the modules for logging.
23
+ class CustomJsonFormatter(jsonlogger.JsonFormatter):
24
+ def add_fields(self, log_record, record, message_dict):
25
+ super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
26
+ if not log_record.get('timestamp'):
27
+ log_record['timestamp'] = record.created
28
+ if log_record.get('severity'):
29
+ log_record['severity'] = log_record['severity'].upper()
30
+ else:
31
+ log_record['severity'] = record.levelname
32
+
33
+ def getJSONLogger(name):
34
+ logger = logging.getLogger(name)
35
+ handler = logging.StreamHandler(sys.stdout)
36
+ formatter = CustomJsonFormatter('%(timestamp)s %(severity)s %(name)s %(message)s')
37
+ handler.setFormatter(formatter)
38
+ logger.addHandler(handler)
39
+ logger.setLevel(logging.INFO)
40
+ logger.propagate = False
41
+ return logger
benchmark/boutique/codedefect/86/code/frontend/deployment_details.go ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "net/http"
5
+ "os"
6
+ "time"
7
+
8
+ "cloud.google.com/go/compute/metadata"
9
+ "github.com/sirupsen/logrus"
10
+ )
11
+
12
+ var deploymentDetailsMap map[string]string
13
+ var log *logrus.Logger
14
+
15
+ func init() {
16
+ initializeLogger()
17
+ // Use a goroutine to ensure loadDeploymentDetails()'s GCP API
18
+ // calls don't block non-GCP deployments. See issue #685.
19
+ go loadDeploymentDetails()
20
+ }
21
+
22
+ func initializeLogger() {
23
+ log = logrus.New()
24
+ log.Level = logrus.DebugLevel
25
+ log.Formatter = &logrus.JSONFormatter{
26
+ FieldMap: logrus.FieldMap{
27
+ logrus.FieldKeyTime: "timestamp",
28
+ logrus.FieldKeyLevel: "severity",
29
+ logrus.FieldKeyMsg: "message",
30
+ },
31
+ TimestampFormat: time.RFC3339Nano,
32
+ }
33
+ log.Out = os.Stdout
34
+ }
35
+
36
+ func loadDeploymentDetails() {
37
+ deploymentDetailsMap = make(map[string]string)
38
+ var metaServerClient = metadata.NewClient(&http.Client{})
39
+
40
+ podHostname, err := os.Hostname()
41
+ if err != nil {
42
+ log.Error("Failed to fetch the hostname for the Pod", err)
43
+ }
44
+
45
+ podCluster, err := metaServerClient.InstanceAttributeValue("cluster-name")
46
+ if err != nil {
47
+ log.Error("Failed to fetch the name of the cluster in which the pod is running", err)
48
+ }
49
+
50
+ podZone, err := metaServerClient.Zone()
51
+ if err != nil {
52
+ log.Error("Failed to fetch the Zone of the node where the pod is scheduled", err)
53
+ }
54
+
55
+ deploymentDetailsMap["HOSTNAME"] = podHostname
56
+ deploymentDetailsMap["CLUSTERNAME"] = podCluster
57
+ deploymentDetailsMap["ZONE"] = podZone
58
+
59
+ log.WithFields(logrus.Fields{
60
+ "cluster": podCluster,
61
+ "zone": podZone,
62
+ "hostname": podHostname,
63
+ }).Debug("Loaded deployment details")
64
+ }
benchmark/boutique/codedefect/86/code/frontend/handlers.go ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "encoding/json"
20
+ "fmt"
21
+ "html/template"
22
+ "io"
23
+ "math/rand"
24
+ "net"
25
+ "net/http"
26
+ "os"
27
+ "strconv"
28
+ "strings"
29
+ "time"
30
+
31
+ "github.com/gorilla/mux"
32
+ "github.com/pkg/errors"
33
+ "github.com/sirupsen/logrus"
34
+
35
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/frontend/genproto"
36
+ "github.com/GoogleCloudPlatform/microservices-demo/src/frontend/money"
37
+ "github.com/GoogleCloudPlatform/microservices-demo/src/frontend/validator"
38
+ )
39
+
40
+ type platformDetails struct {
41
+ css string
42
+ provider string
43
+ }
44
+
45
+ var (
46
+ frontendMessage = strings.TrimSpace(os.Getenv("FRONTEND_MESSAGE"))
47
+ isCymbalBrand = "true" == strings.ToLower(os.Getenv("CYMBAL_BRANDING"))
48
+ assistantEnabled = "true" == strings.ToLower(os.Getenv("ENABLE_ASSISTANT"))
49
+ templates = template.Must(template.New("").
50
+ Funcs(template.FuncMap{
51
+ "renderMoney": renderMoney,
52
+ "renderCurrencyLogo": renderCurrencyLogo,
53
+ }).ParseGlob("templates/*.html"))
54
+ plat platformDetails
55
+ )
56
+
57
+ var validEnvs = []string{"local", "gcp", "azure", "aws", "onprem", "alibaba"}
58
+
59
+ func (fe *frontendServer) homeHandler(w http.ResponseWriter, r *http.Request) {
60
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
61
+ log.WithField("currency", currentCurrency(r)).Info("home")
62
+ currencies, err := fe.getCurrencies(r.Context())
63
+ if err != nil {
64
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve currencies"), http.StatusInternalServerError)
65
+ return
66
+ }
67
+ products, err := fe.getProducts(r.Context())
68
+ if err != nil {
69
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve products"), http.StatusInternalServerError)
70
+ return
71
+ }
72
+ cart, err := fe.getCart(r.Context(), sessionID(r))
73
+ if err != nil {
74
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve cart"), http.StatusInternalServerError)
75
+ return
76
+ }
77
+
78
+ type productView struct {
79
+ Item *pb.Product
80
+ Price *pb.Money
81
+ }
82
+ ps := make([]productView, len(products))
83
+ for i, p := range products {
84
+ price, err := fe.convertCurrency(r.Context(), p.GetPriceUsd(), currentCurrency(r))
85
+ if err != nil {
86
+ renderHTTPError(log, r, w, errors.Wrapf(err, "failed to do currency conversion for product %s", p.GetId()), http.StatusInternalServerError)
87
+ return
88
+ }
89
+ ps[i] = productView{p, price}
90
+ }
91
+
92
+ // Set ENV_PLATFORM (default to local if not set; use env var if set; otherwise detect GCP, which overrides env)_
93
+ var env = os.Getenv("ENV_PLATFORM")
94
+ // Only override from env variable if set + valid env
95
+ if env == "" || stringinSlice(validEnvs, env) == false {
96
+ fmt.Println("env platform is either empty or invalid")
97
+ env = "local"
98
+ }
99
+ // Autodetect GCP
100
+ addrs, err := net.LookupHost("metadata.google.internal.")
101
+ if err == nil && len(addrs) >= 0 {
102
+ log.Debugf("Detected Google metadata server: %v, setting ENV_PLATFORM to GCP.", addrs)
103
+ env = "gcp"
104
+ }
105
+
106
+ log.Debugf("ENV_PLATFORM is: %s", env)
107
+ plat = platformDetails{}
108
+ plat.setPlatformDetails(strings.ToLower(env))
109
+
110
+ if err := templates.ExecuteTemplate(w, "home", injectCommonTemplateData(r, map[string]interface{}{
111
+ "show_currency": true,
112
+ "currencies": currencies,
113
+ "products": ps,
114
+ "cart_size": cartSize(cart),
115
+ "banner_color": os.Getenv("BANNER_COLOR"), // illustrates canary deployments
116
+ "ad": fe.chooseAd(r.Context(), []string{}, log),
117
+ })); err != nil {
118
+ log.Error(err)
119
+ }
120
+ }
121
+
122
+ func (plat *platformDetails) setPlatformDetails(env string) {
123
+ if env == "aws" {
124
+ plat.provider = "AWS"
125
+ plat.css = "aws-platform"
126
+ } else if env == "onprem" {
127
+ plat.provider = "On-Premises"
128
+ plat.css = "onprem-platform"
129
+ } else if env == "azure" {
130
+ plat.provider = "Azure"
131
+ plat.css = "azure-platform"
132
+ } else if env == "gcp" {
133
+ plat.provider = "Google Cloud"
134
+ plat.css = "gcp-platform"
135
+ } else if env == "alibaba" {
136
+ plat.provider = "Alibaba Cloud"
137
+ plat.css = "alibaba-platform"
138
+ } else {
139
+ plat.provider = "local"
140
+ plat.css = "local"
141
+ }
142
+ }
143
+
144
+ func (fe *frontendServer) productHandler(w http.ResponseWriter, r *http.Request) {
145
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
146
+ id := mux.Vars(r)["id"]
147
+ if id == "" {
148
+ renderHTTPError(log, r, w, errors.New("product id not specified"), http.StatusBadRequest)
149
+ return
150
+ }
151
+ log.WithField("id", id).WithField("currency", currentCurrency(r)).
152
+ Debug("serving product page")
153
+
154
+ p, err := fe.getProduct(r.Context(), id)
155
+ if err != nil {
156
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve product"), http.StatusInternalServerError)
157
+ return
158
+ }
159
+ currencies, err := fe.getCurrencies(r.Context())
160
+ if err != nil {
161
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve currencies"), http.StatusInternalServerError)
162
+ return
163
+ }
164
+
165
+ cart, err := fe.getCart(r.Context(), sessionID(r))
166
+ if err != nil {
167
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve cart"), http.StatusInternalServerError)
168
+ return
169
+ }
170
+
171
+ price, err := fe.convertCurrency(r.Context(), p.GetPriceUsd(), currentCurrency(r))
172
+ if err != nil {
173
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to convert currency"), http.StatusInternalServerError)
174
+ return
175
+ }
176
+
177
+ // ignores the error retrieving recommendations since it is not critical
178
+ recommendations, err := fe.getRecommendations(r.Context(), sessionID(r), []string{id})
179
+ if err != nil {
180
+ log.WithField("error", err).Warn("failed to get product recommendations")
181
+ }
182
+
183
+ product := struct {
184
+ Item *pb.Product
185
+ Price *pb.Money
186
+ }{p, price}
187
+
188
+ // Fetch packaging info (weight/dimensions) of the product
189
+ // The packaging service is an optional microservice you can run as part of a Google Cloud demo.
190
+ var packagingInfo *PackagingInfo = nil
191
+ if isPackagingServiceConfigured() {
192
+ packagingInfo, err = httpGetPackagingInfo(id)
193
+ if err != nil {
194
+ fmt.Println("Failed to obtain product's packaging info:", err)
195
+ }
196
+ }
197
+
198
+ if err := templates.ExecuteTemplate(w, "product", injectCommonTemplateData(r, map[string]interface{}{
199
+ "ad": fe.chooseAd(r.Context(), p.Categories, log),
200
+ "show_currency": true,
201
+ "currencies": currencies,
202
+ "product": product,
203
+ "recommendations": recommendations,
204
+ "cart_size": cartSize(cart),
205
+ "packagingInfo": packagingInfo,
206
+ })); err != nil {
207
+ log.Println(err)
208
+ }
209
+ }
210
+
211
+ func (fe *frontendServer) addToCartHandler(w http.ResponseWriter, r *http.Request) {
212
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
213
+ quantity, _ := strconv.ParseUint(r.FormValue("quantity"), 10, 32)
214
+ productID := r.FormValue("product_id")
215
+ payload := validator.AddToCartPayload{
216
+ Quantity: quantity,
217
+ ProductID: productID,
218
+ }
219
+ if err := payload.Validate(); err != nil {
220
+ renderHTTPError(log, r, w, validator.ValidationErrorResponse(err), http.StatusUnprocessableEntity)
221
+ return
222
+ }
223
+ log.WithField("product", payload.ProductID).WithField("quantity", payload.Quantity).Debug("adding to cart")
224
+
225
+ p, err := fe.getProduct(r.Context(), payload.ProductID)
226
+ if err != nil {
227
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve product"), http.StatusInternalServerError)
228
+ return
229
+ }
230
+
231
+ if err := fe.insertCart(r.Context(), sessionID(r), p.GetId(), int32(payload.Quantity)); err != nil {
232
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to add to cart"), http.StatusInternalServerError)
233
+ return
234
+ }
235
+ w.Header().Set("location", baseUrl + "/cart")
236
+ w.WriteHeader(http.StatusFound)
237
+ }
238
+
239
+ func (fe *frontendServer) emptyCartHandler(w http.ResponseWriter, r *http.Request) {
240
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
241
+ log.Debug("emptying cart")
242
+
243
+ if err := fe.emptyCart(r.Context(), sessionID(r)); err != nil {
244
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to empty cart"), http.StatusInternalServerError)
245
+ return
246
+ }
247
+ w.Header().Set("location", baseUrl + "/")
248
+ w.WriteHeader(http.StatusFound)
249
+ }
250
+
251
+ func (fe *frontendServer) viewCartHandler(w http.ResponseWriter, r *http.Request) {
252
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
253
+ log.Debug("view user cart")
254
+ currencies, err := fe.getCurrencies(r.Context())
255
+ if err != nil {
256
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve currencies"), http.StatusInternalServerError)
257
+ return
258
+ }
259
+ cart, err := fe.getCart(r.Context(), sessionID(r))
260
+ if err != nil {
261
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve cart"), http.StatusInternalServerError)
262
+ return
263
+ }
264
+
265
+ // ignores the error retrieving recommendations since it is not critical
266
+ recommendations, err := fe.getRecommendations(r.Context(), sessionID(r), cartIDs(cart))
267
+ if err != nil {
268
+ log.WithField("error", err).Warn("failed to get product recommendations")
269
+ }
270
+
271
+ shippingCost, err := fe.getShippingQuote(r.Context(), cart, currentCurrency(r))
272
+ if err != nil {
273
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to get shipping quote"), http.StatusInternalServerError)
274
+ return
275
+ }
276
+
277
+ type cartItemView struct {
278
+ Item *pb.Product
279
+ Quantity int32
280
+ Price *pb.Money
281
+ }
282
+ items := make([]cartItemView, len(cart))
283
+ totalPrice := pb.Money{CurrencyCode: currentCurrency(r)}
284
+ for i, item := range cart {
285
+ p, err := fe.getProduct(r.Context(), item.GetProductId())
286
+ if err != nil {
287
+ renderHTTPError(log, r, w, errors.Wrapf(err, "could not retrieve product #%s", item.GetProductId()), http.StatusInternalServerError)
288
+ return
289
+ }
290
+ price, err := fe.convertCurrency(r.Context(), p.GetPriceUsd(), currentCurrency(r))
291
+ if err != nil {
292
+ renderHTTPError(log, r, w, errors.Wrapf(err, "could not convert currency for product #%s", item.GetProductId()), http.StatusInternalServerError)
293
+ return
294
+ }
295
+
296
+ multPrice := money.MultiplySlow(*price, uint32(item.GetQuantity()))
297
+ items[i] = cartItemView{
298
+ Item: p,
299
+ Quantity: item.GetQuantity(),
300
+ Price: &multPrice}
301
+ totalPrice = money.Must(money.Sum(totalPrice, multPrice))
302
+ }
303
+ totalPrice = money.Must(money.Sum(totalPrice, *shippingCost))
304
+ year := time.Now().Year()
305
+
306
+ if err := templates.ExecuteTemplate(w, "cart", injectCommonTemplateData(r, map[string]interface{}{
307
+ "currencies": currencies,
308
+ "recommendations": recommendations,
309
+ "cart_size": cartSize(cart),
310
+ "shipping_cost": shippingCost,
311
+ "show_currency": true,
312
+ "total_cost": totalPrice,
313
+ "items": items,
314
+ "expiration_years": []int{year, year + 1, year + 2, year + 3, year + 4},
315
+ })); err != nil {
316
+ log.Println(err)
317
+ }
318
+ }
319
+
320
+ func (fe *frontendServer) placeOrderHandler(w http.ResponseWriter, r *http.Request) {
321
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
322
+ log.Debug("placing order")
323
+
324
+ var (
325
+ email = r.FormValue("email")
326
+ streetAddress = r.FormValue("street_address")
327
+ zipCode, _ = strconv.ParseInt(r.FormValue("zip_code"), 10, 32)
328
+ city = r.FormValue("city")
329
+ state = r.FormValue("state")
330
+ country = r.FormValue("country")
331
+ ccNumber = r.FormValue("credit_card_number")
332
+ ccMonth, _ = strconv.ParseInt(r.FormValue("credit_card_expiration_month"), 10, 32)
333
+ ccYear, _ = strconv.ParseInt(r.FormValue("credit_card_expiration_year"), 10, 32)
334
+ ccCVV, _ = strconv.ParseInt(r.FormValue("credit_card_cvv"), 10, 32)
335
+ )
336
+
337
+ payload := validator.PlaceOrderPayload{
338
+ Email: email,
339
+ StreetAddress: streetAddress,
340
+ ZipCode: zipCode,
341
+ City: city,
342
+ State: state,
343
+ Country: country,
344
+ CcNumber: ccNumber,
345
+ CcMonth: ccMonth,
346
+ CcYear: ccYear,
347
+ CcCVV: ccCVV,
348
+ }
349
+ if err := payload.Validate(); err != nil {
350
+ renderHTTPError(log, r, w, validator.ValidationErrorResponse(err), http.StatusUnprocessableEntity)
351
+ return
352
+ }
353
+
354
+ order, err := pb.NewCheckoutServiceClient(fe.checkoutSvcConn).
355
+ PlaceOrder(r.Context(), &pb.PlaceOrderRequest{
356
+ Email: payload.Email,
357
+ CreditCard: &pb.CreditCardInfo{
358
+ CreditCardNumber: payload.CcNumber,
359
+ CreditCardExpirationMonth: int32(payload.CcMonth),
360
+ CreditCardExpirationYear: int32(payload.CcYear),
361
+ CreditCardCvv: int32(payload.CcCVV)},
362
+ UserId: sessionID(r),
363
+ UserCurrency: currentCurrency(r),
364
+ Address: &pb.Address{
365
+ StreetAddress: payload.StreetAddress,
366
+ City: payload.City,
367
+ State: payload.State,
368
+ ZipCode: int32(payload.ZipCode),
369
+ Country: payload.Country},
370
+ })
371
+ if err != nil {
372
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to complete the order"), http.StatusInternalServerError)
373
+ return
374
+ }
375
+ log.WithField("order", order.GetOrder().GetOrderId()).Info("order placed")
376
+
377
+ order.GetOrder().GetItems()
378
+ recommendations, _ := fe.getRecommendations(r.Context(), sessionID(r), nil)
379
+
380
+ totalPaid := *order.GetOrder().GetShippingCost()
381
+ for _, v := range order.GetOrder().GetItems() {
382
+ multPrice := money.MultiplySlow(*v.GetCost(), uint32(v.GetItem().GetQuantity()))
383
+ totalPaid = money.Must(money.Sum(totalPaid, multPrice))
384
+ }
385
+
386
+ currencies, err := fe.getCurrencies(r.Context())
387
+ if err != nil {
388
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve currencies"), http.StatusInternalServerError)
389
+ return
390
+ }
391
+
392
+ if err := templates.ExecuteTemplate(w, "order", injectCommonTemplateData(r, map[string]interface{}{
393
+ "show_currency": false,
394
+ "currencies": currencies,
395
+ "order": order.GetOrder(),
396
+ "total_paid": &totalPaid,
397
+ "recommendations": recommendations,
398
+ })); err != nil {
399
+ log.Println(err)
400
+ }
401
+ }
402
+
403
+ func (fe *frontendServer) assistantHandler(w http.ResponseWriter, r *http.Request) {
404
+ currencies, err := fe.getCurrencies(r.Context())
405
+ if err != nil {
406
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve currencies"), http.StatusInternalServerError)
407
+ return
408
+ }
409
+
410
+ if err := templates.ExecuteTemplate(w, "assistant", injectCommonTemplateData(r, map[string]interface{}{
411
+ "show_currency": false,
412
+ "currencies": currencies,
413
+ })); err != nil {
414
+ log.Println(err)
415
+ }
416
+ }
417
+
418
+ func (fe *frontendServer) logoutHandler(w http.ResponseWriter, r *http.Request) {
419
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
420
+ log.Debug("logging out")
421
+ for _, c := range r.Cookies() {
422
+ c.Expires = time.Now().Add(-time.Hour * 24 * 365)
423
+ c.MaxAge = -1
424
+ http.SetCookie(w, c)
425
+ }
426
+ w.Header().Set("Location", baseUrl + "/")
427
+ w.WriteHeader(http.StatusFound)
428
+ }
429
+
430
+ func (fe *frontendServer) getProductByID(w http.ResponseWriter, r *http.Request) {
431
+ id := mux.Vars(r)["ids"]
432
+ if id == "" {
433
+ return
434
+ }
435
+
436
+ p, err := fe.getProduct(r.Context(), id)
437
+ if err != nil {
438
+ return
439
+ }
440
+
441
+ jsonData, err := json.Marshal(p)
442
+ if err != nil {
443
+ fmt.Println(err)
444
+ return
445
+ }
446
+
447
+ w.Write(jsonData)
448
+ w.WriteHeader(http.StatusOK)
449
+ }
450
+
451
+ func (fe *frontendServer) chatBotHandler(w http.ResponseWriter, r *http.Request) {
452
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
453
+ type Response struct {
454
+ Message string `json:"message"`
455
+ }
456
+
457
+ type LLMResponse struct {
458
+ Content string `json:"content"`
459
+ Details map[string]any `json:"details"`
460
+ }
461
+
462
+ var response LLMResponse
463
+
464
+ url := "http://" + fe.shoppingAssistantSvcAddr
465
+ req, err := http.NewRequest(http.MethodPost, url, r.Body)
466
+ if err != nil {
467
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to create request"), http.StatusInternalServerError)
468
+ return
469
+ }
470
+ req.Header.Set("Content-Type", "application/json")
471
+ req.Header.Set("Accept", "application/json")
472
+ res, err := http.DefaultClient.Do(req)
473
+ if err != nil {
474
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to send request"), http.StatusInternalServerError)
475
+ return
476
+ }
477
+
478
+ body, err := io.ReadAll(res.Body)
479
+ if err != nil {
480
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to read response"), http.StatusInternalServerError)
481
+ return
482
+ }
483
+
484
+ fmt.Printf("%+v\n", body)
485
+ fmt.Printf("%+v\n", res)
486
+
487
+ err = json.Unmarshal(body, &response)
488
+ if err != nil {
489
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to unmarshal body"), http.StatusInternalServerError)
490
+ return
491
+ }
492
+
493
+ // respond with the same message
494
+ json.NewEncoder(w).Encode(Response{Message: response.Content})
495
+
496
+ w.WriteHeader(http.StatusOK)
497
+ }
498
+
499
+ func (fe *frontendServer) setCurrencyHandler(w http.ResponseWriter, r *http.Request) {
500
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
501
+ cur := r.FormValue("currency_code")
502
+ payload := validator.SetCurrencyPayload{Currency: cur}
503
+ if err := payload.Validate(); err != nil {
504
+ renderHTTPError(log, r, w, validator.ValidationErrorResponse(err), http.StatusUnprocessableEntity)
505
+ return
506
+ }
507
+ log.WithField("curr.new", payload.Currency).WithField("curr.old", currentCurrency(r)).
508
+ Debug("setting currency")
509
+
510
+ if payload.Currency != "" {
511
+ http.SetCookie(w, &http.Cookie{
512
+ Name: cookieCurrency,
513
+ Value: payload.Currency,
514
+ MaxAge: cookieMaxAge,
515
+ })
516
+ }
517
+ referer := r.Header.Get("referer")
518
+ if referer == "" {
519
+ referer = baseUrl + "/"
520
+ }
521
+ w.Header().Set("Location", referer)
522
+ w.WriteHeader(http.StatusFound)
523
+ }
524
+
525
+ // chooseAd queries for advertisements available and randomly chooses one, if
526
+ // available. It ignores the error retrieving the ad since it is not critical.
527
+ func (fe *frontendServer) chooseAd(ctx context.Context, ctxKeys []string, log logrus.FieldLogger) *pb.Ad {
528
+ ads, err := fe.getAd(ctx, ctxKeys)
529
+ if err != nil {
530
+ log.WithField("error", err).Warn("failed to retrieve ads")
531
+ return nil
532
+ }
533
+ return ads[rand.Intn(len(ads))]
534
+ }
535
+
536
+ func renderHTTPError(log logrus.FieldLogger, r *http.Request, w http.ResponseWriter, err error, code int) {
537
+ log.WithField("error", err).Error("request error")
538
+ errMsg := fmt.Sprintf("%+v", err)
539
+
540
+ w.WriteHeader(code)
541
+
542
+ if templateErr := templates.ExecuteTemplate(w, "error", injectCommonTemplateData(r, map[string]interface{}{
543
+ "error": errMsg,
544
+ "status_code": code,
545
+ "status": http.StatusText(code),
546
+ })); templateErr != nil {
547
+ log.Println(templateErr)
548
+ }
549
+ }
550
+
551
+ func injectCommonTemplateData(r *http.Request, payload map[string]interface{}) map[string]interface{} {
552
+ data := map[string]interface{}{
553
+ "session_id": sessionID(r),
554
+ "request_id": r.Context().Value(ctxKeyRequestID{}),
555
+ "user_currency": currentCurrency(r),
556
+ "platform_css": plat.css,
557
+ "platform_name": plat.provider,
558
+ "is_cymbal_brand": isCymbalBrand,
559
+ "assistant_enabled": assistantEnabled,
560
+ "deploymentDetails": deploymentDetailsMap,
561
+ "frontendMessage": frontendMessage,
562
+ "currentYear": time.Now().Year(),
563
+ "baseUrl": baseUrl,
564
+ }
565
+
566
+ for k, v := range payload {
567
+ data[k] = v
568
+ }
569
+
570
+ return data
571
+ }
572
+
573
+ func currentCurrency(r *http.Request) string {
574
+ c, _ := r.Cookie(cookieCurrency)
575
+ if c != nil {
576
+ return c.Value
577
+ }
578
+ return defaultCurrency
579
+ }
580
+
581
+ func sessionID(r *http.Request) string {
582
+ v := r.Context().Value(ctxKeySessionID{})
583
+ if v != nil {
584
+ return v.(string)
585
+ }
586
+ return ""
587
+ }
588
+
589
+ func cartIDs(c []*pb.CartItem) []string {
590
+ out := make([]string, len(c))
591
+ for i, v := range c {
592
+ out[i] = v.GetProductId()
593
+ }
594
+ return out
595
+ }
596
+
597
+ // get total # of items in cart
598
+ func cartSize(c []*pb.CartItem) int {
599
+ cartSize := 0
600
+ for _, item := range c {
601
+ cartSize += int(item.GetQuantity())
602
+ }
603
+ return cartSize
604
+ }
605
+
606
+ func renderMoney(money pb.Money) string {
607
+ currencyLogo := renderCurrencyLogo(money.GetCurrencyCode())
608
+ return fmt.Sprintf("%s%d.%02d", currencyLogo, money.GetUnits(), money.GetNanos()/10000000)
609
+ }
610
+
611
+ func renderCurrencyLogo(currencyCode string) string {
612
+ logos := map[string]string{
613
+ "USD": "$",
614
+ "CAD": "$",
615
+ "JPY": "¥",
616
+ "EUR": "€",
617
+ "TRY": "₺",
618
+ "GBP": "£",
619
+ }
620
+
621
+ logo := "$" //default
622
+ if val, ok := logos[currencyCode]; ok {
623
+ logo = val
624
+ }
625
+ return logo
626
+ }
627
+
628
+ func stringinSlice(slice []string, val string) bool {
629
+ for _, item := range slice {
630
+ if item == val {
631
+ return true
632
+ }
633
+ }
634
+ return false
635
+ }
benchmark/boutique/codedefect/86/code/frontend/main.go ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "fmt"
20
+ "net/http"
21
+ "os"
22
+ "time"
23
+
24
+ "cloud.google.com/go/profiler"
25
+ "github.com/gorilla/mux"
26
+ "github.com/pkg/errors"
27
+ "github.com/sirupsen/logrus"
28
+ "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
29
+ "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
30
+ "go.opentelemetry.io/otel"
31
+ "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
32
+ "go.opentelemetry.io/otel/propagation"
33
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
34
+ "google.golang.org/grpc"
35
+ "google.golang.org/grpc/credentials/insecure"
36
+ )
37
+
38
+ const (
39
+ port = "8080"
40
+ defaultCurrency = "USD"
41
+ cookieMaxAge = 60 * 60 * 48
42
+
43
+ cookiePrefix = "shop_"
44
+ cookieSessionID = cookiePrefix + "session-id"
45
+ cookieCurrency = cookiePrefix + "currency"
46
+ )
47
+
48
+ var (
49
+ whitelistedCurrencies = map[string]bool{
50
+ "USD": true,
51
+ "EUR": true,
52
+ "CAD": true,
53
+ "JPY": true,
54
+ "GBP": true,
55
+ "TRY": true,
56
+ }
57
+
58
+ baseUrl = ""
59
+ )
60
+
61
+ type ctxKeySessionID struct{}
62
+
63
+ type frontendServer struct {
64
+ productCatalogSvcAddr string
65
+ productCatalogSvcConn *grpc.ClientConn
66
+
67
+ currencySvcAddr string
68
+ currencySvcConn *grpc.ClientConn
69
+
70
+ cartSvcAddr string
71
+ cartSvcConn *grpc.ClientConn
72
+
73
+ recommendationSvcAddr string
74
+ recommendationSvcConn *grpc.ClientConn
75
+
76
+ checkoutSvcAddr string
77
+ checkoutSvcConn *grpc.ClientConn
78
+
79
+ shippingSvcAddr string
80
+ shippingSvcConn *grpc.ClientConn
81
+
82
+ adSvcAddr string
83
+ adSvcConn *grpc.ClientConn
84
+
85
+ collectorAddr string
86
+ collectorConn *grpc.ClientConn
87
+
88
+ shoppingAssistantSvcAddr string
89
+ }
90
+
91
+ func main() {
92
+ ctx := context.Background()
93
+ log := logrus.New()
94
+ log.Level = logrus.DebugLevel
95
+ log.Formatter = &logrus.JSONFormatter{
96
+ FieldMap: logrus.FieldMap{
97
+ logrus.FieldKeyTime: "timestamp",
98
+ logrus.FieldKeyLevel: "severity",
99
+ logrus.FieldKeyMsg: "message",
100
+ },
101
+ TimestampFormat: time.RFC3339Nano,
102
+ }
103
+ log.Out = os.Stdout
104
+
105
+ svc := new(frontendServer)
106
+
107
+ otel.SetTextMapPropagator(
108
+ propagation.NewCompositeTextMapPropagator(
109
+ propagation.TraceContext{}, propagation.Baggage{}))
110
+
111
+ baseUrl = os.Getenv("BASE_URL")
112
+
113
+ if os.Getenv("ENABLE_TRACING") == "1" {
114
+ log.Info("Tracing enabled.")
115
+ initTracing(log, ctx, svc)
116
+ } else {
117
+ log.Info("Tracing disabled.")
118
+ }
119
+
120
+ if os.Getenv("ENABLE_PROFILER") == "1" {
121
+ log.Info("Profiling enabled.")
122
+ go initProfiling(log, "frontend", "1.0.0")
123
+ } else {
124
+ log.Info("Profiling disabled.")
125
+ }
126
+
127
+ srvPort := port
128
+ if os.Getenv("PORT") != "" {
129
+ srvPort = os.Getenv("PORT")
130
+ }
131
+ addr := os.Getenv("LISTEN_ADDR")
132
+ mustMapEnv(&svc.productCatalogSvcAddr, "PRODUCT_CATALOG_SERVICE_ADDR")
133
+ mustMapEnv(&svc.currencySvcAddr, "CURRENCY_SERVICE_ADDR")
134
+ mustMapEnv(&svc.cartSvcAddr, "CART_SERVICE_ADDR")
135
+ mustMapEnv(&svc.recommendationSvcAddr, "RECOMMENDATION_SERVICE_ADDR")
136
+ mustMapEnv(&svc.checkoutSvcAddr, "CHECKOUT_SERVICE_ADDR")
137
+ mustMapEnv(&svc.shippingSvcAddr, "SHIPPING_SERVICE_ADDR")
138
+ mustMapEnv(&svc.adSvcAddr, "AD_SERVICE_ADDR")
139
+ mustMapEnv(&svc.shoppingAssistantSvcAddr, "SHOPPING_ASSISTANT_SERVICE_ADDR")
140
+
141
+ mustConnGRPC(ctx, &svc.currencySvcConn, svc.currencySvcAddr)
142
+ mustConnGRPC(ctx, &svc.productCatalogSvcConn, svc.productCatalogSvcAddr)
143
+ mustConnGRPC(ctx, &svc.cartSvcConn, svc.cartSvcAddr)
144
+ mustConnGRPC(ctx, &svc.recommendationSvcConn, svc.recommendationSvcAddr)
145
+ mustConnGRPC(ctx, &svc.shippingSvcConn, svc.shippingSvcAddr)
146
+ mustConnGRPC(ctx, &svc.checkoutSvcConn, svc.checkoutSvcAddr)
147
+ mustConnGRPC(ctx, &svc.adSvcConn, svc.adSvcAddr)
148
+
149
+ r := mux.NewRouter()
150
+ r.HandleFunc(baseUrl+"/", svc.homeHandler).Methods(http.MethodGet, http.MethodHead)
151
+ r.HandleFunc(baseUrl+"/product/{id}", svc.productHandler).Methods(http.MethodGet, http.MethodHead)
152
+ r.HandleFunc(baseUrl+"/cart", svc.viewCartHandler).Methods(http.MethodGet, http.MethodHead)
153
+ r.HandleFunc(baseUrl+"/cart", svc.addToCartHandler).Methods(http.MethodPost)
154
+ r.HandleFunc(baseUrl+"/cart/empty", svc.emptyCartHandler).Methods(http.MethodPost)
155
+ r.HandleFunc(baseUrl+"/setCurrency", svc.setCurrencyHandler).Methods(http.MethodPost)
156
+ r.HandleFunc(baseUrl+"/logout", svc.logoutHandler).Methods(http.MethodGet)
157
+ r.HandleFunc(baseUrl+"/cart/checkout", svc.placeOrderHandler).Methods(http.MethodPost)
158
+ r.HandleFunc(baseUrl+"/assistant", svc.assistantHandler).Methods(http.MethodGet)
159
+ r.PathPrefix(baseUrl + "/static/").Handler(http.StripPrefix(baseUrl+"/static/", http.FileServer(http.Dir("./static/"))))
160
+ r.HandleFunc(baseUrl+"/robots.txt", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "User-agent: *\nDisallow: /") })
161
+ r.HandleFunc(baseUrl+"/_healthz", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "ok") })
162
+ r.HandleFunc(baseUrl+"/product-meta/{ids}", svc.getProductByID).Methods(http.MethodGet)
163
+ r.HandleFunc(baseUrl+"/bot", svc.chatBotHandler).Methods(http.MethodPost)
164
+
165
+ var handler http.Handler = r
166
+ handler = &logHandler{log: log, next: handler} // add logging
167
+ handler = ensureSessionID(handler) // add session ID
168
+ handler = otelhttp.NewHandler(handler, "frontend") // add OTel tracing
169
+
170
+ log.Infof("starting server on %s:%s", addr, srvPort)
171
+ log.Fatal(http.ListenAndServe(addr+":"+srvPort, handler))
172
+ }
173
+ func initStats(log logrus.FieldLogger) {
174
+ // TODO(arbrown) Implement OpenTelemtry stats
175
+ }
176
+
177
+ func initTracing(log logrus.FieldLogger, ctx context.Context, svc *frontendServer) (*sdktrace.TracerProvider, error) {
178
+ mustMapEnv(&svc.collectorAddr, "COLLECTOR_SERVICE_ADDR")
179
+ mustConnGRPC(ctx, &svc.collectorConn, svc.collectorAddr)
180
+ exporter, err := otlptracegrpc.New(
181
+ ctx,
182
+ otlptracegrpc.WithGRPCConn(svc.collectorConn))
183
+ if err != nil {
184
+ log.Warnf("warn: Failed to create trace exporter: %v", err)
185
+ }
186
+ tp := sdktrace.NewTracerProvider(
187
+ sdktrace.WithBatcher(exporter),
188
+ sdktrace.WithSampler(sdktrace.AlwaysSample()))
189
+ otel.SetTracerProvider(tp)
190
+
191
+ return tp, err
192
+ }
193
+
194
+ func initProfiling(log logrus.FieldLogger, service, version string) {
195
+ // TODO(ahmetb) this method is duplicated in other microservices using Go
196
+ // since they are not sharing packages.
197
+ for i := 1; i <= 3; i++ {
198
+ log = log.WithField("retry", i)
199
+ if err := profiler.Start(profiler.Config{
200
+ Service: service,
201
+ ServiceVersion: version,
202
+ // ProjectID must be set if not running on GCP.
203
+ // ProjectID: "my-project",
204
+ }); err != nil {
205
+ log.Warnf("warn: failed to start profiler: %+v", err)
206
+ } else {
207
+ log.Info("started Stackdriver profiler")
208
+ return
209
+ }
210
+ d := time.Second * 10 * time.Duration(i)
211
+ log.Debugf("sleeping %v to retry initializing Stackdriver profiler", d)
212
+ time.Sleep(d)
213
+ }
214
+ log.Warn("warning: could not initialize Stackdriver profiler after retrying, giving up")
215
+ }
216
+
217
+ func mustMapEnv(target *string, envKey string) {
218
+ v := os.Getenv(envKey)
219
+ if v == "" {
220
+ panic(fmt.Sprintf("environment variable %q not set", envKey))
221
+ }
222
+ *target = v
223
+ }
224
+
225
+ func mustConnGRPC(ctx context.Context, conn **grpc.ClientConn, addr string) {
226
+ var err error
227
+ _, cancel := context.WithTimeout(ctx, time.Second*3)
228
+ defer cancel()
229
+ *conn, err = grpc.NewClient(addr,
230
+ grpc.WithTransportCredentials(insecure.NewCredentials()),
231
+ grpc.WithStatsHandler(otelgrpc.NewClientHandler()))
232
+ if err != nil {
233
+ panic(errors.Wrapf(err, "grpc: failed to connect %s", addr))
234
+ }
235
+ }
benchmark/boutique/codedefect/86/code/frontend/middleware.go ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "net/http"
20
+ "time"
21
+ "os"
22
+
23
+ "github.com/google/uuid"
24
+ "github.com/sirupsen/logrus"
25
+ )
26
+
27
+ type ctxKeyLog struct{}
28
+ type ctxKeyRequestID struct{}
29
+
30
+ type logHandler struct {
31
+ log *logrus.Logger
32
+ next http.Handler
33
+ }
34
+
35
+ type responseRecorder struct {
36
+ b int
37
+ status int
38
+ w http.ResponseWriter
39
+ }
40
+
41
+ func (r *responseRecorder) Header() http.Header { return r.w.Header() }
42
+
43
+ func (r *responseRecorder) Write(p []byte) (int, error) {
44
+ if r.status == 0 {
45
+ r.status = http.StatusOK
46
+ }
47
+ n, err := r.w.Write(p)
48
+ r.b += n
49
+ return n, err
50
+ }
51
+
52
+ func (r *responseRecorder) WriteHeader(statusCode int) {
53
+ r.status = statusCode
54
+ r.w.WriteHeader(statusCode)
55
+ }
56
+
57
+ func (lh *logHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
58
+ ctx := r.Context()
59
+ requestID, _ := uuid.NewRandom()
60
+ ctx = context.WithValue(ctx, ctxKeyRequestID{}, requestID.String())
61
+
62
+ start := time.Now()
63
+ rr := &responseRecorder{w: w}
64
+ log := lh.log.WithFields(logrus.Fields{
65
+ "http.req.path": r.URL.Path,
66
+ "http.req.method": r.Method,
67
+ "http.req.id": requestID.String(),
68
+ })
69
+ if v, ok := r.Context().Value(ctxKeySessionID{}).(string); ok {
70
+ log = log.WithField("session", v)
71
+ }
72
+ log.Debug("request started")
73
+ defer func() {
74
+ log.WithFields(logrus.Fields{
75
+ "http.resp.took_ms": int64(time.Since(start) / time.Millisecond),
76
+ "http.resp.status": rr.status,
77
+ "http.resp.bytes": rr.b}).Debugf("request complete")
78
+ }()
79
+
80
+ ctx = context.WithValue(ctx, ctxKeyLog{}, log)
81
+ r = r.WithContext(ctx)
82
+ lh.next.ServeHTTP(rr, r)
83
+ }
84
+
85
+ func ensureSessionID(next http.Handler) http.HandlerFunc {
86
+ return func(w http.ResponseWriter, r *http.Request) {
87
+ var sessionID string
88
+ c, err := r.Cookie(cookieSessionID)
89
+ if err == http.ErrNoCookie {
90
+ if os.Getenv("ENABLE_SINGLE_SHARED_SESSION") == "true" {
91
+ // Hard coded user id, shared across sessions
92
+ sessionID = "12345678-1234-1234-1234-123456789123"
93
+ } else {
94
+ u, _ := uuid.NewRandom()
95
+ sessionID = u.String()
96
+ }
97
+ http.SetCookie(w, &http.Cookie{
98
+ Name: cookieSessionID,
99
+ Value: sessionID,
100
+ MaxAge: cookieMaxAge,
101
+ })
102
+ } else if err != nil {
103
+ return
104
+ } else {
105
+ sessionID = c.Value
106
+ }
107
+ ctx := context.WithValue(r.Context(), ctxKeySessionID{}, sessionID)
108
+ r = r.WithContext(ctx)
109
+ next.ServeHTTP(w, r)
110
+ }
111
+ }
benchmark/boutique/codedefect/86/code/frontend/money/money.go ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package money
16
+
17
+ import (
18
+ "errors"
19
+
20
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/frontend/genproto"
21
+ )
22
+
23
+ const (
24
+ nanosMin = -999999999
25
+ nanosMax = +999999999
26
+ nanosMod = 1000000000
27
+ )
28
+
29
+ var (
30
+ ErrInvalidValue = errors.New("one of the specified money values is invalid")
31
+ ErrMismatchingCurrency = errors.New("mismatching currency codes")
32
+ )
33
+
34
+ // IsValid checks if specified value has a valid units/nanos signs and ranges.
35
+ func IsValid(m pb.Money) bool {
36
+ return signMatches(m) && validNanos(m.GetNanos())
37
+ }
38
+
39
+ func signMatches(m pb.Money) bool {
40
+ return m.GetNanos() == 0 || m.GetUnits() == 0 || (m.GetNanos() < 0) == (m.GetUnits() < 0)
41
+ }
42
+
43
+ func validNanos(nanos int32) bool { return nanosMin <= nanos && nanos <= nanosMax }
44
+
45
+ // IsZero returns true if the specified money value is equal to zero.
46
+ func IsZero(m pb.Money) bool { return m.GetUnits() == 0 && m.GetNanos() == 0 }
47
+
48
+ // IsPositive returns true if the specified money value is valid and is
49
+ // positive.
50
+ func IsPositive(m pb.Money) bool {
51
+ return IsValid(m) && m.GetUnits() > 0 || (m.GetUnits() == 0 && m.GetNanos() > 0)
52
+ }
53
+
54
+ // IsNegative returns true if the specified money value is valid and is
55
+ // negative.
56
+ func IsNegative(m pb.Money) bool {
57
+ return IsValid(m) && m.GetUnits() < 0 || (m.GetUnits() == 0 && m.GetNanos() < 0)
58
+ }
59
+
60
+ // AreSameCurrency returns true if values l and r have a currency code and
61
+ // they are the same values.
62
+ func AreSameCurrency(l, r pb.Money) bool {
63
+ return l.GetCurrencyCode() == r.GetCurrencyCode() && l.GetCurrencyCode() != ""
64
+ }
65
+
66
+ // AreEquals returns true if values l and r are the equal, including the
67
+ // currency. This does not check validity of the provided values.
68
+ func AreEquals(l, r pb.Money) bool {
69
+ return l.GetCurrencyCode() == r.GetCurrencyCode() &&
70
+ l.GetUnits() == r.GetUnits() && l.GetNanos() == r.GetNanos()
71
+ }
72
+
73
+ // Negate returns the same amount with the sign negated.
74
+ func Negate(m pb.Money) pb.Money {
75
+ return pb.Money{
76
+ Units: -m.GetUnits(),
77
+ Nanos: -m.GetNanos(),
78
+ CurrencyCode: m.GetCurrencyCode()}
79
+ }
80
+
81
+ // Must panics if the given error is not nil. This can be used with other
82
+ // functions like: "m := Must(Sum(a,b))".
83
+ func Must(v pb.Money, err error) pb.Money {
84
+ if err != nil {
85
+ panic(err)
86
+ }
87
+ return v
88
+ }
89
+
90
+ // Sum adds two values. Returns an error if one of the values are invalid or
91
+ // currency codes are not matching (unless currency code is unspecified for
92
+ // both).
93
+ func Sum(l, r pb.Money) (pb.Money, error) {
94
+ if !IsValid(l) || !IsValid(r) {
95
+ return pb.Money{}, ErrInvalidValue
96
+ } else if l.GetCurrencyCode() != r.GetCurrencyCode() {
97
+ return pb.Money{}, ErrMismatchingCurrency
98
+ }
99
+ units := l.GetUnits() + r.GetUnits()
100
+ nanos := l.GetNanos() + r.GetNanos()
101
+
102
+ if (units == 0 && nanos == 0) || (units > 0 && nanos >= 0) || (units < 0 && nanos <= 0) {
103
+ // same sign <units, nanos>
104
+ units += int64(nanos / nanosMod)
105
+ nanos = nanos % nanosMod
106
+ } else {
107
+ // different sign. nanos guaranteed to not to go over the limit
108
+ if units > 0 {
109
+ units--
110
+ nanos += nanosMod
111
+ } else {
112
+ units++
113
+ nanos -= nanosMod
114
+ }
115
+ }
116
+
117
+ return pb.Money{
118
+ Units: units,
119
+ Nanos: nanos,
120
+ CurrencyCode: l.GetCurrencyCode()}, nil
121
+ }
122
+
123
+ // MultiplySlow is a slow multiplication operation done through adding the value
124
+ // to itself n-1 times.
125
+ func MultiplySlow(m pb.Money, n uint32) pb.Money {
126
+ out := m
127
+ for n > 1 {
128
+ out = Must(Sum(out, m))
129
+ n--
130
+ }
131
+ return out
132
+ }
benchmark/boutique/codedefect/86/code/frontend/packaging_info.go ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "encoding/json"
19
+ "fmt"
20
+ "io/ioutil"
21
+ "net/http"
22
+ "os"
23
+ )
24
+
25
+ /*
26
+ As part of an optional Google Cloud demo, you can run an additional "packaging" microservice (HTTP server).
27
+ This file contains code related to the frontend and the "packaging" microservice.
28
+ */
29
+
30
+ var (
31
+ packagingServiceUrl string
32
+ )
33
+
34
+ type PackagingInfo struct {
35
+ Weight float32 `json:"weight"`
36
+ Width float32 `json:"width"`
37
+ Height float32 `json:"height"`
38
+ Depth float32 `json:"depth"`
39
+ }
40
+
41
+ // init() is a special function in Golang that will run when this package is imported.
42
+ func init() {
43
+ packagingServiceUrl = os.Getenv("PACKAGING_SERVICE_URL")
44
+ }
45
+
46
+ func isPackagingServiceConfigured() bool {
47
+ return packagingServiceUrl != ""
48
+ }
49
+
50
+ func httpGetPackagingInfo(productId string) (*PackagingInfo, error) {
51
+ // Make the GET request
52
+ url := packagingServiceUrl + "/" + productId
53
+ fmt.Println("Requesting packaging info from URL: ", url)
54
+ resp, err := http.Get(url)
55
+ if err != nil {
56
+ return nil, err
57
+ }
58
+ defer resp.Body.Close()
59
+
60
+ // Check the response status code
61
+ if resp.StatusCode != http.StatusOK {
62
+ return nil, fmt.Errorf("Unexpected status code: %d", resp.StatusCode)
63
+ }
64
+
65
+ // Read the JSON response body
66
+ responseBody, err := ioutil.ReadAll(resp.Body)
67
+ if err != nil {
68
+ return nil, err
69
+ }
70
+
71
+ // Decode the JSON response into a PackagingInfo struct
72
+ var packagingInfo PackagingInfo
73
+ err = json.Unmarshal(responseBody, &packagingInfo)
74
+ if err != nil {
75
+ return nil, err
76
+ }
77
+
78
+ return &packagingInfo, nil
79
+ }
benchmark/boutique/codedefect/86/code/frontend/rpc.go ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "time"
20
+
21
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/frontend/genproto"
22
+
23
+ "github.com/pkg/errors"
24
+ )
25
+
26
+ const (
27
+ avoidNoopCurrencyConversionRPC = false
28
+ )
29
+
30
+ func (fe *frontendServer) getCurrencies(ctx context.Context) ([]string, error) {
31
+ currs, err := pb.NewCurrencyServiceClient(fe.currencySvcConn).
32
+ GetSupportedCurrencies(ctx, &pb.Empty{})
33
+ if err != nil {
34
+ return nil, err
35
+ }
36
+ var out []string
37
+ for _, c := range currs.CurrencyCodes {
38
+ if _, ok := whitelistedCurrencies[c]; ok {
39
+ out = append(out, c)
40
+ }
41
+ }
42
+ return out, nil
43
+ }
44
+
45
+ func (fe *frontendServer) getProducts(ctx context.Context) ([]*pb.Product, error) {
46
+ resp, err := pb.NewProductCatalogServiceClient(fe.productCatalogSvcConn).
47
+ ListProducts(ctx, &pb.Empty{})
48
+ return resp.GetProducts(), err
49
+ }
50
+
51
+ func (fe *frontendServer) getProduct(ctx context.Context, id string) (*pb.Product, error) {
52
+ resp, err := pb.NewProductCatalogServiceClient(fe.productCatalogSvcConn).
53
+ GetProduct(ctx, &pb.GetProductRequest{Id: id})
54
+ return resp, err
55
+ }
56
+
57
+ func (fe *frontendServer) getCart(ctx context.Context, userID string) ([]*pb.CartItem, error) {
58
+ resp, err := pb.NewCartServiceClient(fe.cartSvcConn).GetCart(ctx, &pb.GetCartRequest{UserId: userID})
59
+ return resp.GetItems(), err
60
+ }
61
+
62
+ func (fe *frontendServer) emptyCart(ctx context.Context, userID string) error {
63
+ _, err := pb.NewCartServiceClient(fe.cartSvcConn).EmptyCart(ctx, &pb.EmptyCartRequest{UserId: userID})
64
+ return err
65
+ }
66
+
67
+ func (fe *frontendServer) insertCart(ctx context.Context, userID, productID string, quantity int32) error {
68
+ _, err := pb.NewCartServiceClient(fe.cartSvcConn).AddItem(ctx, &pb.AddItemRequest{
69
+ UserId: userID,
70
+ Item: &pb.CartItem{
71
+ ProductId: productID,
72
+ Quantity: quantity},
73
+ })
74
+ return err
75
+ }
76
+
77
+ func (fe *frontendServer) convertCurrency(ctx context.Context, money *pb.Money, currency string) (*pb.Money, error) {
78
+ if avoidNoopCurrencyConversionRPC && money.GetCurrencyCode() == currency {
79
+ return money, nil
80
+ }
81
+ return pb.NewCurrencyServiceClient(fe.currencySvcConn).
82
+ Convert(ctx, &pb.CurrencyConversionRequest{
83
+ From: money,
84
+ ToCode: currency})
85
+ }
86
+
87
+ func (fe *frontendServer) getShippingQuote(ctx context.Context, items []*pb.CartItem, currency string) (*pb.Money, error) {
88
+ quote, err := pb.NewShippingServiceClient(fe.shippingSvcConn).GetQuote(ctx,
89
+ &pb.GetQuoteRequest{
90
+ Address: nil,
91
+ Items: items})
92
+ if err != nil {
93
+ return nil, err
94
+ }
95
+ localized, err := fe.convertCurrency(ctx, quote.GetCostUsd(), currency)
96
+ return localized, errors.Wrap(err, "failed to convert currency for shipping cost")
97
+ }
98
+
99
+ func (fe *frontendServer) getRecommendations(ctx context.Context, userID string, productIDs []string) ([]*pb.Product, error) {
100
+ resp, err := pb.NewRecommendationServiceClient(fe.recommendationSvcConn).ListRecommendations(ctx,
101
+ &pb.ListRecommendationsRequest{UserId: userID, ProductIds: productIDs})
102
+ if err != nil {
103
+ return nil, err
104
+ }
105
+ out := make([]*pb.Product, len(resp.GetProductIds()))
106
+ for i, v := range resp.GetProductIds() {
107
+ p, err := fe.getProduct(ctx, v)
108
+ if err != nil {
109
+ return nil, errors.Wrapf(err, "failed to get recommended product info (#%s)", v)
110
+ }
111
+ out[i] = p
112
+ }
113
+ if len(out) > 4 {
114
+ out = out[:4] // take only first four to fit the UI
115
+ }
116
+ return out, err
117
+ }
118
+
119
+ func (fe *frontendServer) getAd(ctx context.Context, ctxKeys []string) ([]*pb.Ad, error) {
120
+ ctx, cancel := context.WithTimeout(ctx, time.Millisecond*100)
121
+ defer cancel()
122
+
123
+ resp, err := pb.NewAdServiceClient(fe.adSvcConn).GetAds(ctx, &pb.AdRequest{
124
+ ContextKeys: ctxKeys,
125
+ })
126
+ return resp.GetAds(), errors.Wrap(err, "failed to get ads")
127
+ }
benchmark/boutique/codedefect/86/code/frontend/validator/validator.go ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package validator
16
+
17
+ import (
18
+ "errors"
19
+ "fmt"
20
+
21
+ "github.com/go-playground/validator/v10"
22
+ )
23
+
24
+ var validate *validator.Validate
25
+
26
+ // init() is a special function that will run when this package is imported.
27
+ // It instantiates a SINGLE instance of *validator.Validate with the added
28
+ // benefit of caching struct info and validations.
29
+ func init() {
30
+ validate = validator.New(validator.WithRequiredStructEnabled())
31
+ }
32
+
33
+ type Payload interface {
34
+ Validate() error
35
+ }
36
+
37
+ type AddToCartPayload struct {
38
+ Quantity uint64 `validate:"required,gte=1,lte=10"`
39
+ ProductID string `validate:"required"`
40
+ }
41
+
42
+ type PlaceOrderPayload struct {
43
+ Email string `validate:"required,email"`
44
+ StreetAddress string `validate:"required,max=512"`
45
+ ZipCode int64 `validate:"required"`
46
+ City string `validate:"required,max=128"`
47
+ State string `validate:"required,max=128"`
48
+ Country string `validate:"required,max=128"`
49
+ CcNumber string `validate:"required,credit_card"`
50
+ CcMonth int64 `validate:"required,gte=1,lte=12"`
51
+ CcYear int64 `validate:"required"`
52
+ CcCVV int64 `validate:"required"`
53
+ }
54
+
55
+ type SetCurrencyPayload struct {
56
+ Currency string `validate:"required,iso4217"`
57
+ }
58
+
59
+ // Implementations of the 'Payload' interface.
60
+ func (ad *AddToCartPayload) Validate() error {
61
+ return validate.Struct(ad)
62
+ }
63
+
64
+ func (po *PlaceOrderPayload) Validate() error {
65
+ return validate.Struct(po)
66
+ }
67
+
68
+ func (sc *SetCurrencyPayload) Validate() error {
69
+ return validate.Struct(sc)
70
+ }
71
+
72
+ // Reusable error response function.
73
+ func ValidationErrorResponse(err error) error {
74
+ validationErrs, ok := err.(validator.ValidationErrors)
75
+ if !ok {
76
+ return errors.New("invalid validation error format")
77
+ }
78
+ var msg string
79
+ for _, err := range validationErrs {
80
+ msg += fmt.Sprintf("Field '%s' is invalid: %s\n", err.Field(), err.Tag())
81
+ }
82
+ return fmt.Errorf("%s", msg)
83
+ }
benchmark/boutique/codedefect/86/code/paymentservice/charge.js ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ const cardValidator = require('simple-card-validator');
16
+ const { v4: uuidv4 } = require('uuid');
17
+ const pino = require('pino');
18
+
19
+ const logger = pino({
20
+ name: 'paymentservice-charge',
21
+ messageKey: 'message',
22
+ formatters: {
23
+ level (logLevelString, logLevelNum) {
24
+ return { severity: logLevelString }
25
+ }
26
+ }
27
+ });
28
+
29
+
30
+ class CreditCardError extends Error {
31
+ constructor (message) {
32
+ super(message);
33
+ this.code = 400; // Invalid argument error
34
+ }
35
+ }
36
+
37
+ class InvalidCreditCard extends CreditCardError {
38
+ constructor (cardType) {
39
+ super(`Credit card info is invalid`);
40
+ }
41
+ }
42
+
43
+ class UnacceptedCreditCard extends CreditCardError {
44
+ constructor (cardType) {
45
+ super(`Sorry, we cannot process ${cardType} credit cards. Only VISA or MasterCard is accepted.`);
46
+ }
47
+ }
48
+
49
+ class ExpiredCreditCard extends CreditCardError {
50
+ constructor (number, month, year) {
51
+ super(`Your credit card (ending ${number.substr(-4)}) expired on ${month}/${year}`);
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Verifies the credit card number and (pretend) charges the card.
57
+ *
58
+ * @param {*} request
59
+ * @return transaction_id - a random uuid.
60
+ */
61
+ module.exports = function charge (request) {
62
+ const { amount, credit_card: creditCard } = request;
63
+ const cardNumber = creditCard.credit_card_number;
64
+ const cardInfo = cardValidator(cardNumber);
65
+ const {
66
+ card_type: cardType,
67
+ valid
68
+ } = cardInfo.getCardDetails();
69
+
70
+ if (!valid) { throw new InvalidCreditCard(); }
71
+
72
+ // Only VISA and mastercard is accepted, other card types (AMEX, dinersclub) will
73
+ // throw UnacceptedCreditCard error.
74
+ if (!(cardType === 'visa' || cardType === 'mastercard')) { throw new UnacceptedCreditCard(cardType); }
75
+
76
+ // Also validate expiration is > today.
77
+ const currentMonth = new Date().getMonth() + 1;
78
+ const currentYear = new Date().getFullYear();
79
+ const { credit_card_expiration_year: year, credit_card_expiration_month: month } = creditCard;
80
+ if ((currentYear * 12 + currentMonth) > (year * 12 + month)) { throw new ExpiredCreditCard(cardNumber.replace('-', ''), month, year); }
81
+
82
+ logger.info(`Transaction processed: ${cardType} ending ${cardNumber.substr(-4)} \
83
+ Amount: ${amount.currency_code}${amount.units}.${amount.nanos}`);
84
+
85
+ return { transaction_id: uuidv4() };
86
+ };
benchmark/boutique/codedefect/86/code/paymentservice/index.js ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2018 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ const logger = require('./logger')
20
+
21
+ if (process.env.DISABLE_PROFILER) {
22
+ logger.info("Profiler disabled.")
23
+ } else {
24
+ logger.info("Profiler enabled.")
25
+ require('@google-cloud/profiler').start({
26
+ serviceContext: {
27
+ service: 'paymentservice',
28
+ version: '1.0.0'
29
+ }
30
+ });
31
+ }
32
+
33
+
34
+ if (process.env.ENABLE_TRACING == "1") {
35
+ logger.info("Tracing enabled.")
36
+
37
+ const { resourceFromAttributes } = require('@opentelemetry/resources');
38
+
39
+ const { ATTR_SERVICE_NAME }= require('@opentelemetry/semantic-conventions');
40
+
41
+ const { GrpcInstrumentation } = require('@opentelemetry/instrumentation-grpc');
42
+ const { registerInstrumentations } = require('@opentelemetry/instrumentation');
43
+ const opentelemetry = require('@opentelemetry/sdk-node');
44
+
45
+ const { OTLPTraceExporter } = require('@opentelemetry/exporter-otlp-grpc');
46
+
47
+ const collectorUrl = process.env.COLLECTOR_SERVICE_ADDR;
48
+ const traceExporter = new OTLPTraceExporter({url: collectorUrl});
49
+
50
+ const sdk = new opentelemetry.NodeSDK({
51
+ resource: resourceFromAttributes({
52
+ [ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || 'paymentservice',
53
+ }),
54
+ traceExporter: traceExporter,
55
+ });
56
+
57
+ registerInstrumentations({
58
+ instrumentations: [new GrpcInstrumentation()]
59
+ });
60
+
61
+ sdk.start()
62
+ } else {
63
+ logger.info("Tracing disabled.")
64
+ }
65
+
66
+
67
+ const path = require('path');
68
+ const HipsterShopServer = require('./server');
69
+
70
+ const PORT = process.env['PORT'];
71
+ const PROTO_PATH = path.join(__dirname, '/proto/');
72
+
73
+ const server = new HipsterShopServer(PROTO_PATH, PORT);
74
+
75
+ server.listen();
benchmark/boutique/codedefect/86/code/paymentservice/logger.js ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2023 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ const pino = require('pino');
18
+
19
+ module.exports = pino({
20
+ name: 'paymentservice-server',
21
+ messageKey: 'message',
22
+ formatters: {
23
+ level (logLevelString, logLevelNum) {
24
+ return { severity: logLevelString }
25
+ }
26
+ }
27
+ });
benchmark/boutique/codedefect/86/code/paymentservice/server.js ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ const path = require('path');
16
+ const grpc = require('@grpc/grpc-js');
17
+ const protoLoader = require('@grpc/proto-loader');
18
+
19
+ const charge = require('./charge');
20
+
21
+ const logger = require('./logger')
22
+
23
+ class HipsterShopServer {
24
+ constructor(protoRoot, port = HipsterShopServer.PORT) {
25
+ this.port = port;
26
+
27
+ this.packages = {
28
+ hipsterShop: this.loadProto(path.join(protoRoot, 'demo.proto')),
29
+ health: this.loadProto(path.join(protoRoot, 'grpc/health/v1/health.proto'))
30
+ };
31
+
32
+ this.server = new grpc.Server();
33
+ this.loadAllProtos(protoRoot);
34
+ }
35
+
36
+ /**
37
+ * Handler for PaymentService.Charge.
38
+ * @param {*} call { ChargeRequest }
39
+ * @param {*} callback fn(err, ChargeResponse)
40
+ */
41
+ static ChargeServiceHandler(call, callback) {
42
+ try {
43
+ logger.info(`PaymentService#Charge invoked with request ${JSON.stringify(call.request)}`);
44
+ const response = charge(call.request);
45
+ callback(null, response);
46
+ } catch (err) {
47
+ console.warn(err);
48
+ callback(err);
49
+ }
50
+ }
51
+
52
+ static CheckHandler(call, callback) {
53
+ callback(null, { status: 'SERVING' });
54
+ }
55
+
56
+
57
+ listen() {
58
+ const server = this.server
59
+ const port = this.port
60
+ server.bindAsync(
61
+ `[::]:${port}`,
62
+ grpc.ServerCredentials.createInsecure(),
63
+ function () {
64
+ logger.info(`PaymentService gRPC server started on port ${port}`);
65
+ server.start();
66
+ }
67
+ );
68
+ }
69
+
70
+ loadProto(path) {
71
+ const packageDefinition = protoLoader.loadSync(
72
+ path,
73
+ {
74
+ keepCase: true,
75
+ longs: String,
76
+ enums: String,
77
+ defaults: true,
78
+ oneofs: true
79
+ }
80
+ );
81
+ return grpc.loadPackageDefinition(packageDefinition);
82
+ }
83
+
84
+ loadAllProtos(protoRoot) {
85
+ const hipsterShopPackage = this.packages.hipsterShop.hipstershop;
86
+ const healthPackage = this.packages.health.grpc.health.v1;
87
+
88
+ this.server.addService(
89
+ hipsterShopPackage.PaymentService.service,
90
+ {
91
+ charge: HipsterShopServer.ChargeServiceHandler.bind(this)
92
+ }
93
+ );
94
+
95
+ this.server.addService(
96
+ healthPackage.Health.service,
97
+ {
98
+ check: HipsterShopServer.CheckHandler.bind(this)
99
+ }
100
+ );
101
+ }
102
+ }
103
+
104
+ HipsterShopServer.PORT = process.env.PORT;
105
+
106
+ module.exports = HipsterShopServer;
benchmark/boutique/codedefect/86/code/productcatalogservice/catalog_loader.go ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // https://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "bytes"
19
+ "context"
20
+ "fmt"
21
+ "net"
22
+ "os"
23
+ "strings"
24
+
25
+ "cloud.google.com/go/alloydbconn"
26
+ secretmanager "cloud.google.com/go/secretmanager/apiv1"
27
+ "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
28
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/productcatalogservice/genproto"
29
+ "github.com/golang/protobuf/jsonpb"
30
+ "github.com/jackc/pgx/v5/pgxpool"
31
+ )
32
+
33
+ func loadCatalog(catalog *pb.ListProductsResponse) error {
34
+ catalogMutex.Lock()
35
+ defer catalogMutex.Unlock()
36
+
37
+ if os.Getenv("ALLOYDB_CLUSTER_NAME") != "" {
38
+ return loadCatalogFromAlloyDB(catalog)
39
+ }
40
+
41
+ return loadCatalogFromLocalFile(catalog)
42
+ }
43
+
44
+ func loadCatalogFromLocalFile(catalog *pb.ListProductsResponse) error {
45
+ log.Info("loading catalog from local products.json file...")
46
+
47
+ catalogJSON, err := os.ReadFile("products.json")
48
+ if err != nil {
49
+ log.Warnf("failed to open product catalog json file: %v", err)
50
+ return err
51
+ }
52
+
53
+ if err := jsonpb.Unmarshal(bytes.NewReader(catalogJSON), catalog); err != nil {
54
+ log.Warnf("failed to parse the catalog JSON: %v", err)
55
+ return err
56
+ }
57
+
58
+ log.Info("successfully parsed product catalog json")
59
+ return nil
60
+ }
61
+
62
+ func getSecretPayload(project, secret, version string) (string, error) {
63
+ ctx := context.Background()
64
+ client, err := secretmanager.NewClient(ctx)
65
+ if err != nil {
66
+ log.Warnf("failed to create SecretManager client: %v", err)
67
+ return "", err
68
+ }
69
+ defer client.Close()
70
+
71
+ req := &secretmanagerpb.AccessSecretVersionRequest{
72
+ Name: fmt.Sprintf("projects/%s/secrets/%s/versions/%s", project, secret, version),
73
+ }
74
+
75
+ // Call the API.
76
+ result, err := client.AccessSecretVersion(ctx, req)
77
+ if err != nil {
78
+ log.Warnf("failed to access SecretVersion: %v", err)
79
+ return "", err
80
+ }
81
+
82
+ return string(result.Payload.Data), nil
83
+ }
84
+
85
+ func loadCatalogFromAlloyDB(catalog *pb.ListProductsResponse) error {
86
+ log.Info("loading catalog from AlloyDB...")
87
+
88
+ projectID := os.Getenv("PROJECT_ID")
89
+ region := os.Getenv("REGION")
90
+ pgClusterName := os.Getenv("ALLOYDB_CLUSTER_NAME")
91
+ pgInstanceName := os.Getenv("ALLOYDB_INSTANCE_NAME")
92
+ pgDatabaseName := os.Getenv("ALLOYDB_DATABASE_NAME")
93
+ pgTableName := os.Getenv("ALLOYDB_TABLE_NAME")
94
+ pgSecretName := os.Getenv("ALLOYDB_SECRET_NAME")
95
+
96
+ pgPassword, err := getSecretPayload(projectID, pgSecretName, "latest")
97
+ if err != nil {
98
+ return err
99
+ }
100
+
101
+ dialer, err := alloydbconn.NewDialer(context.Background())
102
+ if err != nil {
103
+ log.Warnf("failed to set-up dialer connection: %v", err)
104
+ return err
105
+ }
106
+ cleanup := func() error { return dialer.Close() }
107
+ defer cleanup()
108
+
109
+ dsn := fmt.Sprintf(
110
+ "user=%s password=%s dbname=%s sslmode=disable",
111
+ "postgres", pgPassword, pgDatabaseName,
112
+ )
113
+
114
+ config, err := pgxpool.ParseConfig(dsn)
115
+ if err != nil {
116
+ log.Warnf("failed to parse DSN config: %v", err)
117
+ return err
118
+ }
119
+
120
+ pgInstanceURI := fmt.Sprintf("projects/%s/locations/%s/clusters/%s/instances/%s", projectID, region, pgClusterName, pgInstanceName)
121
+ config.ConnConfig.DialFunc = func(ctx context.Context, _ string, _ string) (net.Conn, error) {
122
+ return dialer.Dial(ctx, pgInstanceURI)
123
+ }
124
+
125
+ pool, err := pgxpool.NewWithConfig(context.Background(), config)
126
+ if err != nil {
127
+ log.Warnf("failed to set-up pgx pool: %v", err)
128
+ return err
129
+ }
130
+ defer pool.Close()
131
+
132
+ query := "SELECT id, name, description, picture, price_usd_currency_code, price_usd_units, price_usd_nanos, categories FROM " + pgTableName
133
+ rows, err := pool.Query(context.Background(), query)
134
+ if err != nil {
135
+ log.Warnf("failed to query database: %v", err)
136
+ return err
137
+ }
138
+ defer rows.Close()
139
+
140
+ catalog.Products = catalog.Products[:0]
141
+ for rows.Next() {
142
+ product := &pb.Product{}
143
+ product.PriceUsd = &pb.Money{}
144
+
145
+ var categories string
146
+ err = rows.Scan(&product.Id, &product.Name, &product.Description,
147
+ &product.Picture, &product.PriceUsd.CurrencyCode, &product.PriceUsd.Units,
148
+ &product.PriceUsd.Nanos, &categories)
149
+ if err != nil {
150
+ log.Warnf("failed to scan query result row: %v", err)
151
+ return err
152
+ }
153
+ categories = strings.ToLower(categories)
154
+ product.Categories = strings.Split(categories, ",")
155
+
156
+ catalog.Products = append(catalog.Products, product)
157
+ }
158
+
159
+ log.Info("successfully parsed product catalog from AlloyDB")
160
+ return nil
161
+ }
benchmark/boutique/codedefect/86/code/productcatalogservice/product_catalog.go ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "strings"
20
+ "time"
21
+
22
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/productcatalogservice/genproto"
23
+ "google.golang.org/grpc/codes"
24
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
25
+ "google.golang.org/grpc/status"
26
+ )
27
+
28
+ type productCatalog struct {
29
+ pb.UnimplementedProductCatalogServiceServer
30
+ catalog pb.ListProductsResponse
31
+ }
32
+
33
+ func (p *productCatalog) Check(ctx context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
34
+ return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
35
+ }
36
+
37
+ func (p *productCatalog) Watch(req *healthpb.HealthCheckRequest, ws healthpb.Health_WatchServer) error {
38
+ return status.Errorf(codes.Unimplemented, "health check via Watch not implemented")
39
+ }
40
+
41
+ func (p *productCatalog) ListProducts(context.Context, *pb.Empty) (*pb.ListProductsResponse, error) {
42
+ time.Sleep(extraLatency)
43
+
44
+ return &pb.ListProductsResponse{Products: p.parseCatalog()}, nil
45
+ }
46
+
47
+ func (p *productCatalog) GetProduct(ctx context.Context, req *pb.GetProductRequest) (*pb.Product, error) {
48
+ time.Sleep(extraLatency)
49
+
50
+ catalog := p.parseCatalog()
51
+ for _, product := range catalog {
52
+ if req.Id == product.Id {
53
+ return product, nil
54
+ }
55
+ }
56
+
57
+ return nil, status.Errorf(codes.NotFound, "no product with ID %s", req.Id)
58
+ }
59
+
60
+ func (p *productCatalog) SearchProducts(ctx context.Context, req *pb.SearchProductsRequest) (*pb.SearchProductsResponse, error) {
61
+ time.Sleep(extraLatency)
62
+
63
+ var ps []*pb.Product
64
+ for _, product := range p.parseCatalog() {
65
+ if strings.Contains(strings.ToLower(product.Name), strings.ToLower(req.Query)) ||
66
+ strings.Contains(strings.ToLower(product.Description), strings.ToLower(req.Query)) {
67
+ ps = append(ps, product)
68
+ }
69
+ }
70
+
71
+ return &pb.SearchProductsResponse{Results: ps}, nil
72
+ }
73
+
74
+ func (p *productCatalog) parseCatalog() []*pb.Product {
75
+ if reloadCatalog || len(p.catalog.Products) == 0 {
76
+ err := loadCatalog(&p.catalog)
77
+ if err != nil {
78
+ return []*pb.Product{}
79
+ }
80
+ }
81
+
82
+ return p.catalog.Products
83
+ }
benchmark/boutique/codedefect/86/code/productcatalogservice/server.go ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "flag"
20
+ "fmt"
21
+ "net"
22
+ "os"
23
+ "os/signal"
24
+ "sync"
25
+ "syscall"
26
+ "time"
27
+
28
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/productcatalogservice/genproto"
29
+ "google.golang.org/grpc/credentials/insecure"
30
+ "google.golang.org/grpc/health"
31
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
32
+
33
+ "cloud.google.com/go/profiler"
34
+ "github.com/pkg/errors"
35
+ "github.com/sirupsen/logrus"
36
+ "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
37
+ "go.opentelemetry.io/otel"
38
+ "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
39
+ "go.opentelemetry.io/otel/propagation"
40
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
41
+ "google.golang.org/grpc"
42
+ )
43
+
44
+ var (
45
+ catalogMutex *sync.Mutex
46
+ log *logrus.Logger
47
+ extraLatency time.Duration
48
+
49
+ port = "3550"
50
+
51
+ reloadCatalog bool
52
+ )
53
+
54
+ func init() {
55
+ log = logrus.New()
56
+ log.Formatter = &logrus.JSONFormatter{
57
+ FieldMap: logrus.FieldMap{
58
+ logrus.FieldKeyTime: "timestamp",
59
+ logrus.FieldKeyLevel: "severity",
60
+ logrus.FieldKeyMsg: "message",
61
+ },
62
+ TimestampFormat: time.RFC3339Nano,
63
+ }
64
+ log.Out = os.Stdout
65
+ catalogMutex = &sync.Mutex{}
66
+ }
67
+
68
+ func main() {
69
+ if os.Getenv("ENABLE_TRACING") == "1" {
70
+ err := initTracing()
71
+ if err != nil {
72
+ log.Warnf("warn: failed to start tracer: %+v", err)
73
+ }
74
+ } else {
75
+ log.Info("Tracing disabled.")
76
+ }
77
+
78
+ if os.Getenv("DISABLE_PROFILER") == "" {
79
+ log.Info("Profiling enabled.")
80
+ go initProfiling("productcatalogservice", "1.0.0")
81
+ } else {
82
+ log.Info("Profiling disabled.")
83
+ }
84
+
85
+ flag.Parse()
86
+
87
+ // set injected latency
88
+ if s := os.Getenv("EXTRA_LATENCY"); s != "" {
89
+ v, err := time.ParseDuration(s)
90
+ if err != nil {
91
+ log.Fatalf("failed to parse EXTRA_LATENCY (%s) as time.Duration: %+v", v, err)
92
+ }
93
+ extraLatency = v
94
+ log.Infof("extra latency enabled (duration: %v)", extraLatency)
95
+ } else {
96
+ extraLatency = time.Duration(0)
97
+ }
98
+
99
+ sigs := make(chan os.Signal, 1)
100
+ signal.Notify(sigs, syscall.SIGUSR1, syscall.SIGUSR2)
101
+ go func() {
102
+ for {
103
+ sig := <-sigs
104
+ log.Printf("Received signal: %s", sig)
105
+ if sig == syscall.SIGUSR1 {
106
+ reloadCatalog = true
107
+ log.Infof("Enable catalog reloading")
108
+ } else {
109
+ reloadCatalog = false
110
+ log.Infof("Disable catalog reloading")
111
+ }
112
+ }
113
+ }()
114
+
115
+ if os.Getenv("PORT") != "" {
116
+ port = os.Getenv("PORT")
117
+ }
118
+ log.Infof("starting grpc server at :%s", port)
119
+ run(port)
120
+ select {}
121
+ }
122
+
123
+ func run(port string) string {
124
+ listener, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
125
+ if err != nil {
126
+ log.Fatal(err)
127
+ }
128
+
129
+ // Propagate trace context
130
+ otel.SetTextMapPropagator(
131
+ propagation.NewCompositeTextMapPropagator(
132
+ propagation.TraceContext{}, propagation.Baggage{}))
133
+ var srv *grpc.Server
134
+ srv = grpc.NewServer(
135
+ grpc.StatsHandler(otelgrpc.NewServerHandler()))
136
+
137
+ svc := &productCatalog{}
138
+ err = loadCatalog(&svc.catalog)
139
+ if err != nil {
140
+ log.Fatalf("could not parse product catalog: %v", err)
141
+ }
142
+
143
+ pb.RegisterProductCatalogServiceServer(srv, svc)
144
+ healthcheck := health.NewServer()
145
+ healthpb.RegisterHealthServer(srv, healthcheck)
146
+ go srv.Serve(listener)
147
+
148
+ return listener.Addr().String()
149
+ }
150
+
151
+ func initStats() {
152
+ // TODO(drewbr) Implement OpenTelemetry stats
153
+ }
154
+
155
+ func initTracing() error {
156
+ var (
157
+ collectorAddr string
158
+ collectorConn *grpc.ClientConn
159
+ )
160
+
161
+ ctx := context.Background()
162
+
163
+ mustMapEnv(&collectorAddr, "COLLECTOR_SERVICE_ADDR")
164
+ mustConnGRPC(ctx, &collectorConn, collectorAddr)
165
+
166
+ exporter, err := otlptracegrpc.New(
167
+ ctx,
168
+ otlptracegrpc.WithGRPCConn(collectorConn))
169
+ if err != nil {
170
+ log.Warnf("warn: Failed to create trace exporter: %v", err)
171
+ }
172
+ tp := sdktrace.NewTracerProvider(
173
+ sdktrace.WithBatcher(exporter),
174
+ sdktrace.WithSampler(sdktrace.AlwaysSample()))
175
+ otel.SetTracerProvider(tp)
176
+ return err
177
+ }
178
+
179
+ func initProfiling(service, version string) {
180
+ for i := 1; i <= 3; i++ {
181
+ if err := profiler.Start(profiler.Config{
182
+ Service: service,
183
+ ServiceVersion: version,
184
+ // ProjectID must be set if not running on GCP.
185
+ // ProjectID: "my-project",
186
+ }); err != nil {
187
+ log.Warnf("failed to start profiler: %+v", err)
188
+ } else {
189
+ log.Info("started Stackdriver profiler")
190
+ return
191
+ }
192
+ d := time.Second * 10 * time.Duration(i)
193
+ log.Infof("sleeping %v to retry initializing Stackdriver profiler", d)
194
+ time.Sleep(d)
195
+ }
196
+ log.Warn("could not initialize Stackdriver profiler after retrying, giving up")
197
+ }
198
+
199
+ func mustMapEnv(target *string, envKey string) {
200
+ v := os.Getenv(envKey)
201
+ if v == "" {
202
+ panic(fmt.Sprintf("environment variable %q not set", envKey))
203
+ }
204
+ *target = v
205
+ }
206
+
207
+ func mustConnGRPC(ctx context.Context, conn **grpc.ClientConn, addr string) {
208
+ var err error
209
+ _, cancel := context.WithTimeout(ctx, time.Second*3)
210
+ defer cancel()
211
+ *conn, err = grpc.NewClient(addr,
212
+ grpc.WithTransportCredentials(insecure.NewCredentials()),
213
+ grpc.WithStatsHandler(otelgrpc.NewClientHandler()))
214
+ if err != nil {
215
+ panic(errors.Wrapf(err, "grpc: failed to connect %s", addr))
216
+ }
217
+ }
benchmark/boutique/codedefect/86/code/recommendationservice/client.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import sys
18
+ import grpc
19
+ import demo_pb2
20
+ import demo_pb2_grpc
21
+
22
+ from logger import getJSONLogger
23
+ logger = getJSONLogger('recommendationservice-server')
24
+
25
+ if __name__ == "__main__":
26
+ # get port
27
+ if len(sys.argv) > 1:
28
+ port = sys.argv[1]
29
+ else:
30
+ port = "8080"
31
+
32
+ # set up server stub
33
+ channel = grpc.insecure_channel('localhost:'+port)
34
+ stub = demo_pb2_grpc.RecommendationServiceStub(channel)
35
+ # form request
36
+ request = demo_pb2.ListRecommendationsRequest(user_id="test", product_ids=["test"])
37
+ # make call to server
38
+ response = stub.ListRecommendations(request)
39
+ logger.info(response)
benchmark/boutique/codedefect/86/code/recommendationservice/logger.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import logging
18
+ import sys
19
+ from pythonjsonlogger import jsonlogger
20
+
21
+ # TODO(yoshifumi) this class is duplicated since other Python services are
22
+ # not sharing the modules for logging.
23
+ class CustomJsonFormatter(jsonlogger.JsonFormatter):
24
+ def add_fields(self, log_record, record, message_dict):
25
+ super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
26
+ if not log_record.get('timestamp'):
27
+ log_record['timestamp'] = record.created
28
+ if log_record.get('severity'):
29
+ log_record['severity'] = log_record['severity'].upper()
30
+ else:
31
+ log_record['severity'] = record.levelname
32
+
33
+ def getJSONLogger(name):
34
+ logger = logging.getLogger(name)
35
+ handler = logging.StreamHandler(sys.stdout)
36
+ formatter = CustomJsonFormatter('%(timestamp)s %(severity)s %(name)s %(message)s')
37
+ handler.setFormatter(formatter)
38
+ logger.addHandler(handler)
39
+ logger.setLevel(logging.INFO)
40
+ logger.propagate = False
41
+ return logger
benchmark/boutique/codedefect/86/code/recommendationservice/recommendation_server.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+ import random
19
+ import time
20
+ import traceback
21
+ from concurrent import futures
22
+
23
+ # @TODO: Temporarily removed in https://github.com/GoogleCloudPlatform/microservices-demo/pull/3196
24
+ # import googlecloudprofiler
25
+
26
+ from google.auth.exceptions import DefaultCredentialsError
27
+ import grpc
28
+
29
+ import demo_pb2
30
+ import demo_pb2_grpc
31
+ from grpc_health.v1 import health_pb2
32
+ from grpc_health.v1 import health_pb2_grpc
33
+
34
+ from opentelemetry import trace
35
+ from opentelemetry.instrumentation.grpc import GrpcInstrumentorClient, GrpcInstrumentorServer
36
+ from opentelemetry.sdk.trace import TracerProvider
37
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
38
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
39
+
40
+ from logger import getJSONLogger
41
+ logger = getJSONLogger('recommendationservice-server')
42
+
43
+ def initStackdriverProfiling():
44
+ project_id = None
45
+ try:
46
+ project_id = os.environ["GCP_PROJECT_ID"]
47
+ except KeyError:
48
+ # Environment variable not set
49
+ pass
50
+
51
+ # @TODO: Temporarily removed in https://github.com/GoogleCloudPlatform/microservices-demo/pull/3196
52
+ # for retry in range(1,4):
53
+ # try:
54
+ # if project_id:
55
+ # googlecloudprofiler.start(service='recommendation_server', service_version='1.0.0', verbose=0, project_id=project_id)
56
+ # else:
57
+ # googlecloudprofiler.start(service='recommendation_server', service_version='1.0.0', verbose=0)
58
+ # logger.info("Successfully started Stackdriver Profiler.")
59
+ # return
60
+ # except (BaseException) as exc:
61
+ # logger.info("Unable to start Stackdriver Profiler Python agent. " + str(exc))
62
+ # if (retry < 4):
63
+ # logger.info("Sleeping %d seconds to retry Stackdriver Profiler agent initialization"%(retry*10))
64
+ # time.sleep (1)
65
+ # else:
66
+ # logger.warning("Could not initialize Stackdriver Profiler after retrying, giving up")
67
+ return
68
+
69
+ class RecommendationService(demo_pb2_grpc.RecommendationServiceServicer):
70
+ def ListRecommendations(self, request, context):
71
+ max_responses = 5
72
+ # fetch list of products from product catalog stub
73
+ cat_response = product_catalog_stub.ListProducts(demo_pb2.Empty())
74
+ product_ids = [x.id for x in cat_response.products]
75
+ filtered_products = list(set(product_ids)-set(request.product_ids))
76
+ num_products = len(filtered_products)
77
+ num_return = min(max_responses, num_products)
78
+ # sample list of indicies to return
79
+ indices = random.sample(range(num_products), num_return)
80
+ # fetch product ids from indices
81
+ prod_list = [filtered_products[i] for i in indices]
82
+ logger.info("[Recv ListRecommendations] product_ids={}".format(prod_list))
83
+ # build and return response
84
+ response = demo_pb2.ListRecommendationsResponse()
85
+ response.product_ids.extend(prod_list)
86
+ return response
87
+
88
+ def Check(self, request, context):
89
+ return health_pb2.HealthCheckResponse(
90
+ status=health_pb2.HealthCheckResponse.SERVING)
91
+
92
+ def Watch(self, request, context):
93
+ return health_pb2.HealthCheckResponse(
94
+ status=health_pb2.HealthCheckResponse.UNIMPLEMENTED)
95
+
96
+
97
+ if __name__ == "__main__":
98
+ logger.info("initializing recommendationservice")
99
+
100
+ try:
101
+ if "DISABLE_PROFILER" in os.environ:
102
+ raise KeyError()
103
+ else:
104
+ logger.info("Profiler enabled.")
105
+ initStackdriverProfiling()
106
+ except KeyError:
107
+ logger.info("Profiler disabled.")
108
+
109
+ try:
110
+ grpc_client_instrumentor = GrpcInstrumentorClient()
111
+ grpc_client_instrumentor.instrument()
112
+ grpc_server_instrumentor = GrpcInstrumentorServer()
113
+ grpc_server_instrumentor.instrument()
114
+ if os.environ["ENABLE_TRACING"] == "1":
115
+ trace.set_tracer_provider(TracerProvider())
116
+ otel_endpoint = os.getenv("COLLECTOR_SERVICE_ADDR", "localhost:4317")
117
+ trace.get_tracer_provider().add_span_processor(
118
+ BatchSpanProcessor(
119
+ OTLPSpanExporter(
120
+ endpoint = otel_endpoint,
121
+ insecure = True
122
+ )
123
+ )
124
+ )
125
+ except (KeyError, DefaultCredentialsError):
126
+ logger.info("Tracing disabled.")
127
+ except Exception as e:
128
+ logger.warn(f"Exception on Cloud Trace setup: {traceback.format_exc()}, tracing disabled.")
129
+
130
+ port = os.environ.get('PORT', "8080")
131
+ catalog_addr = os.environ.get('PRODUCT_CATALOG_SERVICE_ADDR', '')
132
+ if catalog_addr == "":
133
+ raise Exception('PRODUCT_CATALOG_SERVICE_ADDR environment variable not set')
134
+ logger.info("product catalog address: " + catalog_addr)
135
+ channel = grpc.insecure_channel(catalog_addr)
136
+ product_catalog_stub = demo_pb2_grpc.ProductCatalogServiceStub(channel)
137
+
138
+ # create gRPC server
139
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
140
+
141
+ # add class to gRPC server
142
+ service = RecommendationService()
143
+ demo_pb2_grpc.add_RecommendationServiceServicer_to_server(service, server)
144
+ health_pb2_grpc.add_HealthServicer_to_server(service, server)
145
+
146
+ # start server
147
+ logger.info("listening on port: " + port)
148
+ server.add_insecure_port('[::]:'+port)
149
+ server.start()
150
+
151
+ # keep alive
152
+ try:
153
+ while True:
154
+ time.sleep(10000)
155
+ except KeyboardInterrupt:
156
+ server.stop(0)
benchmark/boutique/codedefect/86/code/shippingservice/main.go ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "fmt"
19
+ "net"
20
+ "os"
21
+ "time"
22
+
23
+ "cloud.google.com/go/profiler"
24
+ "github.com/sirupsen/logrus"
25
+ "golang.org/x/net/context"
26
+ "google.golang.org/grpc"
27
+ "google.golang.org/grpc/codes"
28
+ "google.golang.org/grpc/health"
29
+ "google.golang.org/grpc/reflection"
30
+ "google.golang.org/grpc/status"
31
+
32
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/shippingservice/genproto"
33
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
34
+ )
35
+
36
+ const (
37
+ defaultPort = "50051"
38
+ )
39
+
40
+ var log *logrus.Logger
41
+
42
+ func init() {
43
+ log = logrus.New()
44
+ log.Level = logrus.DebugLevel
45
+ log.Formatter = &logrus.JSONFormatter{
46
+ FieldMap: logrus.FieldMap{
47
+ logrus.FieldKeyTime: "timestamp",
48
+ logrus.FieldKeyLevel: "severity",
49
+ logrus.FieldKeyMsg: "message",
50
+ },
51
+ TimestampFormat: time.RFC3339Nano,
52
+ }
53
+ log.Out = os.Stdout
54
+ }
55
+
56
+ func main() {
57
+ if os.Getenv("DISABLE_TRACING") == "" {
58
+ log.Info("Tracing enabled, but temporarily unavailable")
59
+ log.Info("See https://github.com/GoogleCloudPlatform/microservices-demo/issues/422 for more info.")
60
+ go initTracing()
61
+ } else {
62
+ log.Info("Tracing disabled.")
63
+ }
64
+
65
+ if os.Getenv("DISABLE_PROFILER") == "" {
66
+ log.Info("Profiling enabled.")
67
+ go initProfiling("shippingservice", "1.0.0")
68
+ } else {
69
+ log.Info("Profiling disabled.")
70
+ }
71
+
72
+ port := defaultPort
73
+ if value, ok := os.LookupEnv("PORT"); ok {
74
+ port = value
75
+ }
76
+ port = fmt.Sprintf(":%s", port)
77
+
78
+ lis, err := net.Listen("tcp", port)
79
+ if err != nil {
80
+ log.Fatalf("failed to listen: %v", err)
81
+ }
82
+
83
+ var srv *grpc.Server
84
+ if os.Getenv("DISABLE_STATS") == "" {
85
+ log.Info("Stats enabled, but temporarily unavailable")
86
+ srv = grpc.NewServer()
87
+ } else {
88
+ log.Info("Stats disabled.")
89
+ srv = grpc.NewServer()
90
+ }
91
+ svc := &server{}
92
+ pb.RegisterShippingServiceServer(srv, svc)
93
+ healthcheck := health.NewServer()
94
+ healthpb.RegisterHealthServer(srv, healthcheck)
95
+ log.Infof("Shipping Service listening on port %s", port)
96
+
97
+ // Register reflection service on gRPC server.
98
+ reflection.Register(srv)
99
+ if err := srv.Serve(lis); err != nil {
100
+ log.Fatalf("failed to serve: %v", err)
101
+ }
102
+ }
103
+
104
+ // server controls RPC service responses.
105
+ type server struct {
106
+ pb.UnimplementedShippingServiceServer
107
+ }
108
+
109
+ // Check is for health checking.
110
+ func (s *server) Check(ctx context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
111
+ return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
112
+ }
113
+
114
+ func (s *server) Watch(req *healthpb.HealthCheckRequest, ws healthpb.Health_WatchServer) error {
115
+ return status.Errorf(codes.Unimplemented, "health check via Watch not implemented")
116
+ }
117
+
118
+ // GetQuote produces a shipping quote (cost) in USD.
119
+ func (s *server) GetQuote(ctx context.Context, in *pb.GetQuoteRequest) (*pb.GetQuoteResponse, error) {
120
+ log.Info("[GetQuote] received request")
121
+ defer log.Info("[GetQuote] completed request")
122
+
123
+ // 1. Generate a quote based on the total number of items to be shipped.
124
+ count := 0
125
+ for _, item := range in.Items {
126
+ count += int(item.Quantity)
127
+ }
128
+ quote := CreateQuoteFromCount(count)
129
+
130
+ // 2. Generate a response.
131
+ return &pb.GetQuoteResponse{
132
+ CostUsd: &pb.Money{
133
+ CurrencyCode: "USD",
134
+ Units: int64(quote.Dollars),
135
+ Nanos: int32(quote.Cents * 10000000)},
136
+ }, nil
137
+
138
+ }
139
+
140
+ // ShipOrder mocks that the requested items will be shipped.
141
+ // It supplies a tracking ID for notional lookup of shipment delivery status.
142
+ func (s *server) ShipOrder(ctx context.Context, in *pb.ShipOrderRequest) (*pb.ShipOrderResponse, error) {
143
+ log.Info("[ShipOrder] received request")
144
+ defer log.Info("[ShipOrder] completed request")
145
+ // 1. Create a Tracking ID
146
+ baseAddress := fmt.Sprintf("%s, %s, %s", in.Address.StreetAddress, in.Address.City, in.Address.State)
147
+ id := CreateTrackingId(baseAddress)
148
+
149
+ // 2. Generate a response.
150
+ return &pb.ShipOrderResponse{
151
+ TrackingId: id,
152
+ }, nil
153
+ }
154
+
155
+ func initStats() {
156
+ //TODO(arbrown) Implement OpenTelemetry stats
157
+ }
158
+
159
+ func initTracing() {
160
+ // TODO(arbrown) Implement OpenTelemetry tracing
161
+ }
162
+
163
+ func initProfiling(service, version string) {
164
+ // TODO(ahmetb) this method is duplicated in other microservices using Go
165
+ // since they are not sharing packages.
166
+ for i := 1; i <= 3; i++ {
167
+ if err := profiler.Start(profiler.Config{
168
+ Service: service,
169
+ ServiceVersion: version,
170
+ // ProjectID must be set if not running on GCP.
171
+ // ProjectID: "my-project",
172
+ }); err != nil {
173
+ log.Warnf("failed to start profiler: %+v", err)
174
+ } else {
175
+ log.Info("started Stackdriver profiler")
176
+ return
177
+ }
178
+ d := time.Second * 10 * time.Duration(i)
179
+ log.Infof("sleeping %v to retry initializing Stackdriver profiler", d)
180
+ time.Sleep(d)
181
+ }
182
+ log.Warn("could not initialize Stackdriver profiler after retrying, giving up")
183
+ }
benchmark/boutique/codedefect/86/code/shippingservice/quote.go ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "time"
19
+ "fmt"
20
+ "math"
21
+ )
22
+
23
+ // Quote represents a currency value.
24
+ type Quote struct {
25
+ Dollars uint32
26
+ Cents uint32
27
+ }
28
+
29
+ // String representation of the Quote.
30
+ func (q Quote) String() string {
31
+ return fmt.Sprintf("$%d.%d", q.Dollars, q.Cents)
32
+ }
33
+
34
+ // CreateQuoteFromCount takes a number of items and returns a shipping quote.
35
+ func CreateQuoteFromCount(count int) Quote {
36
+ if count == 0 {
37
+ return CreateQuoteFromFloat(0)
38
+ }
39
+ return CreateQuoteFromFloat(8.99)
40
+ }
41
+
42
+ // CreateQuoteFromFloat takes a price represented as a float and creates a Price struct.
43
+ func CreateQuoteFromFloat(value float64) Quote {
44
+ start := time.Now()
45
+ for {
46
+ if time.Now().Sub(start) > 500*time.Millisecond {
47
+ break
48
+ }
49
+ }
50
+
51
+ units, fraction := math.Modf(value)
52
+ return Quote{
53
+ uint32(units),
54
+ uint32(math.Trunc(fraction * 100)),
55
+ }
56
+ }
benchmark/boutique/codedefect/86/code/shippingservice/tracker.go ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "fmt"
19
+ "math/rand"
20
+ )
21
+
22
+ // CreateTrackingId generates a tracking ID.
23
+ func CreateTrackingId(salt string) string {
24
+ return fmt.Sprintf("%c%c-%d%s-%d%s",
25
+ getRandomLetterCode(),
26
+ getRandomLetterCode(),
27
+ len(salt),
28
+ getRandomNumber(3),
29
+ len(salt)/2,
30
+ getRandomNumber(7),
31
+ )
32
+ }
33
+
34
+ // getRandomLetterCode generates a code point value for a capital letter.
35
+ func getRandomLetterCode() uint32 {
36
+ return 65 + uint32(rand.Intn(25))
37
+ }
38
+
39
+ // getRandomNumber generates a string representation of a number with the requested number of digits.
40
+ func getRandomNumber(digits int) string {
41
+ str := ""
42
+ for i := 0; i < digits; i++ {
43
+ str = fmt.Sprintf("%s%d", str, rand.Intn(10))
44
+ }
45
+
46
+ return str
47
+ }
benchmark/boutique/codedefect/86/metadata.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "namespace": "boutique",
3
+ "query": "Service Performance Degradation.",
4
+ "difficulty": "hard",
5
+ "result": {
6
+ "fault_taxonomy": "Application_Code_Defect",
7
+ "fault_object": "app/shippingservice",
8
+ "root_cause": "code_busy_loop"
9
+ }
10
+ }
benchmark/boutique/codedefect/86/raw_data/alert.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "has_anomalies",
3
+ "alert_count": 2,
4
+ "alerts": [
5
+ {
6
+ "type": "Service",
7
+ "name": "shippingservice",
8
+ "time_range": "2026-05-19 11:54:18 ~ 2026-05-19 11:56:53",
9
+ "status": "ABNORMAL",
10
+ "evidence": [
11
+ "RESOURCE_SATURATION [cpu_cfs] | Val=1.167s throttled",
12
+ "RESOURCE_SATURATION [cpu] | Normal=0.00 cores -> Current=0.13 cores (+12912.5%)",
13
+ "LATENCY_DEGRADATION [Slow Response] | p50latency: Normal=0.36ms -> Current=781.25ms (+217518.2%) | Peak=810.72ms | p90latency: Normal=3.79ms -> Current=1363.16ms (+35867.2%) | Peak=1732.39ms"
14
+ ]
15
+ },
16
+ {
17
+ "type": "Node",
18
+ "name": "worker-01",
19
+ "time_range": "2026-05-19 11:54:18 ~ 2026-05-19 11:56:53",
20
+ "status": "ABNORMAL",
21
+ "evidence": [
22
+ "RESOURCE_SATURATION [cpu utilization] | Normal=3.96% -> Current=6.61% (+66.8%)"
23
+ ]
24
+ }
25
+ ]
26
+ }
benchmark/boutique/codedefect/86/raw_data/k8s_states.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/boutique/codedefect/86/raw_data/logs.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/boutique/codedefect/86/raw_data/metrics.csv ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ time,frontend-cpu,frontend-mem,frontend-cpu_cfs,frontend-rps,frontend-success_rate,frontend-network_receive,frontend-network_transmit,frontend-p50latency,frontend-p90latency,frontend-fs_write_bytes,checkoutservice-cpu,checkoutservice-mem,checkoutservice-cpu_cfs,checkoutservice-rps,checkoutservice-success_rate,checkoutservice-network_receive,checkoutservice-network_transmit,checkoutservice-p50latency,checkoutservice-p90latency,checkoutservice-fs_write_bytes,productcatalogservice-cpu,productcatalogservice-mem,productcatalogservice-cpu_cfs,productcatalogservice-rps,productcatalogservice-success_rate,productcatalogservice-network_receive,productcatalogservice-network_transmit,productcatalogservice-p50latency,productcatalogservice-p90latency,productcatalogservice-fs_write_bytes,cartservice-cpu,cartservice-mem,cartservice-cpu_cfs,cartservice-rps,cartservice-success_rate,cartservice-network_receive,cartservice-network_transmit,cartservice-p50latency,cartservice-p90latency,cartservice-fs_write_bytes,currencyservice-cpu,currencyservice-mem,currencyservice-cpu_cfs,currencyservice-rps,currencyservice-success_rate,currencyservice-network_receive,currencyservice-network_transmit,currencyservice-p50latency,currencyservice-p90latency,currencyservice-fs_write_bytes,paymentservice-cpu,paymentservice-mem,paymentservice-cpu_cfs,paymentservice-rps,paymentservice-success_rate,paymentservice-network_receive,paymentservice-network_transmit,paymentservice-p50latency,paymentservice-p90latency,paymentservice-fs_write_bytes,shippingservice-cpu,shippingservice-mem,shippingservice-cpu_cfs,shippingservice-rps,shippingservice-success_rate,shippingservice-network_receive,shippingservice-network_transmit,shippingservice-p50latency,shippingservice-p90latency,shippingservice-fs_write_bytes,emailservice-cpu,emailservice-mem,emailservice-cpu_cfs,emailservice-rps,emailservice-success_rate,emailservice-network_receive,emailservice-network_transmit,emailservice-p50latency,emailservice-p90latency,emailservice-fs_write_bytes,recommendationservice-cpu,recommendationservice-mem,recommendationservice-cpu_cfs,recommendationservice-rps,recommendationservice-success_rate,recommendationservice-network_receive,recommendationservice-network_transmit,recommendationservice-p50latency,recommendationservice-p90latency,recommendationservice-fs_write_bytes,adservice-cpu,adservice-mem,adservice-cpu_cfs,adservice-rps,adservice-success_rate,adservice-network_receive,adservice-network_transmit,adservice-p50latency,adservice-p90latency,adservice-fs_write_bytes,redis-cart-cpu,redis-cart-mem,redis-cart-cpu_cfs,redis-cart-rps,redis-cart-success_rate,redis-cart-network_receive,redis-cart-network_transmit,redis-cart-p50latency,redis-cart-p90latency,redis-cart-fs_write_bytes,master-cpu,master-mem,master-tcp_retans,worker-01-cpu,worker-01-mem,worker-01-tcp_retans,worker-02-cpu,worker-02-mem,worker-02-tcp_retans,worker-03-cpu,worker-03-mem,worker-03-tcp_retans
2
+ 2026-05-19 11:52:33,0.001,17780736.0,0.0,0.257,1.0,10.15,10.927,21.367,2021.68,0,0.0,10317824.0,0.0,0,0,2.461,1.875,0,0,0,0.001,25616384.0,0.0,1.973,1.0,1.796,1.223,0.285,1.798,0,0.022,76292096.0,0.094,0.0,0.0,3.522,3.124,4.402,1462.24,0,0.001,49946624.0,0.0,0.636,1.0,4.15,3.387,3.143,4.936,0,0.0,30433280.0,0.0,0,0,2.867,2.284,0,0,0,0.0,10559488.0,0.0,0.179,1.0,3.666,2.574,0.423,4.933,0,0.0,89395200.0,0.0,0,0,2.838,2.221,0,0,0,0.001,86773760.0,0.0,0.0,0.0,4.417,3.503,3.652,33.514,0,0.003,162414592.0,0.01,0.0,0.0,4.488,3.562,0.0,0.0,0,0.004,17432576.0,0.0,0,0,3.736,2.739,0,0,0.0,3.936,34.942,0.0,3.503,30.517,0.0,3.497,30.201,0.0,2.989,34.801,0.0
3
+ 2026-05-19 11:52:38,0.002,18808832.0,0.0,0.313,1.0,8.624,9.284,21.002,1571.68,0,0.0,10432512.0,0.0,0,0,2.84,2.13,0,0,0,0.001,25616384.0,0.0,2.395,1.0,5.64,3.927,0.297,2.579,0,0.028,76292096.0,0.122,0.0,0.0,3.522,3.124,4.317,48.544,0,0.002,50069504.0,0.0,0.758,1.0,4.889,4.101,3.125,4.902,0,0.0,30904320.0,0.0,0,0,2.789,2.18,0,0,0,0.0,11415552.0,0.0,0.212,1.0,3.666,2.574,0.417,4.722,0,0.001,89395200.0,0.0,0,0,2.807,2.245,0,0,0,0.001,86773760.0,0.0,0.175,1.0,4.313,3.588,3.309,7.872,0,0.003,162627584.0,0.0,0.0,0.0,3.256,2.377,0.0,0.0,0,0.004,17432576.0,0.0,0,0,4.493,3.245,0,0,0.0,3.865,34.956,0.0,3.503,30.517,0.0,3.549,30.201,0.0,2.989,34.801,0.0
4
+ 2026-05-19 11:52:43,0.002,18808832.0,0.0,0.368,1.0,11.644,12.302,20.765,1121.68,0,0.0,10432512.0,0.0,0,0,2.75,2.077,0,0,0,0.001,25808896.0,0.0,2.817,1.0,7.041,4.884,0.296,2.495,0,0.034,76292096.0,0.147,0.358,1.0,4.8,4.314,3.893,68.135,0,0.002,50069504.0,0.0,1.009,1.0,5.749,4.814,2.967,4.787,0,0.0,30904320.0,0.0,0,0,2.789,2.18,0,0,0,0.0,11415552.0,0.0,0.246,1.0,4.196,2.767,0.401,4.684,0,0.001,89395200.0,0.0,0,0,2.807,2.245,0,0,0,0.002,86794240.0,0.0,0.214,1.0,4.313,3.588,3.278,6.847,0,0.003,162627584.0,0.0,0.077,1.0,3.256,2.377,3.0,4.6,0,0.004,17563648.0,0.0,0,0,4.493,3.245,0,0,0.0,3.865,34.956,0.0,3.496,30.395,0.0,3.549,30.201,0.0,2.937,34.802,0.0
5
+ 2026-05-19 11:52:48,0.002,18808832.0,0.0,0.426,1.0,15.232,16.102,20.002,93.526,0,0.0,10473472.0,0.0,0,0,2.841,2.183,0,0,0,0.001,25808896.0,0.0,2.302,1.0,5.985,4.158,0.286,1.887,0,0.034,76292096.0,0.147,0.425,1.0,4.8,4.314,3.698,76.77,0,0.002,50069504.0,0.0,1.151,1.0,5.749,4.814,2.961,4.757,0,0.0,30904320.0,0.0,0,0,2.7,2.077,0,0,0,0.0,11415552.0,0.0,0.279,1.0,4.007,2.819,0.422,4.604,0,0.001,89395200.0,0.0,0,0,2.832,2.212,0,0,0,0.002,86794240.0,0.0,0.253,1.0,4.775,3.991,3.182,4.928,0,0.003,163082240.0,0.0,0.094,1.0,2.589,1.89,3.0,4.6,0,0.004,17563648.0,0.0,0,0,4.423,3.16,0,0,0.0,3.865,34.956,0.0,3.496,30.395,0.0,3.65,30.172,0.067,3.1,34.802,0.0
6
+ 2026-05-19 11:52:53,0.002,19087360.0,0.0,0.484,1.0,15.232,16.102,19.921,91.516,0,0.0,10473472.0,0.0,0,0,2.841,2.183,0,0,0,0.001,25808896.0,0.0,2.602,1.0,5.985,4.158,0.283,1.646,0,0.025,79470592.0,0.098,0.492,1.0,3.823,3.436,3.684,74.976,0,0.002,50241536.0,0.0,1.293,1.0,5.894,5.149,2.955,4.745,0,0.0,31059968.0,0.0,0,0,2.7,2.077,0,0,0,0.0,11415552.0,0.0,0.312,1.0,4.007,2.819,0.419,4.519,0,0.001,89395200.0,0.0,0,0,2.832,2.212,0,0,0,0.002,86794240.0,0.0,0.25,1.0,4.037,3.375,3.178,4.921,0,0.003,163082240.0,0.0,0.111,1.0,3.427,2.457,3.0,4.6,0,0.004,17563648.0,0.0,0,0,2.624,1.814,0,0,0.0,3.808,34.966,0.0,3.496,30.395,0.0,3.694,30.172,0.067,3.1,34.802,0.0
7
+ 2026-05-19 11:52:58,0.002,19087360.0,0.0,0.543,1.0,14.232,14.82,19.858,90.026,0,0.0,10473472.0,0.0,0,0,2.249,1.729,0,0,0,0.001,25952256.0,0.0,2.902,1.0,7.03,4.932,0.283,1.588,0,0.015,79470592.0,0.034,0.442,1.0,3.423,3.076,3.591,65.578,0,0.002,50241536.0,0.0,1.318,1.0,5.894,5.149,2.829,4.695,0,0.0,31059968.0,0.0,0,0,1.907,1.471,0,0,0,0.0,11415552.0,0.0,0.294,1.0,3.55,2.704,0.413,4.474,0,0.001,89395200.0,0.0,0,0,2.222,1.736,0,0,0,0.002,86794240.0,0.0,0.284,1.0,4.871,4.199,3.165,4.898,0,0.003,163082240.0,0.0,0.106,1.0,3.427,2.457,3.207,4.972,0,0.004,17436672.0,0.0,0,0,2.35,1.625,0,0,0.0,3.808,34.966,0.0,3.471,30.526,0.0,3.694,30.172,0.067,3.231,34.638,0.0
8
+ 2026-05-19 11:53:03,0.002,19087360.0,0.0,0.597,1.0,15.751,16.673,18.422,86.013,0,0.0,10526720.0,0.0,0,0,1.766,1.39,0,0,0,0.001,25952256.0,0.0,3.81,1.0,7.03,4.932,0.281,1.431,0,0.015,79470592.0,0.034,0.495,1.0,4.54,3.858,3.531,61.687,0,0.002,50241536.0,0.0,1.448,1.0,5.894,5.149,2.816,4.691,0,0.0,31059968.0,0.0,0,0,1.75,1.35,0,0,0,0.0,11460608.0,0.0,0.321,1.0,3.275,2.525,0.405,4.447,0,0.001,89395200.0,0.0,0,0,2.412,1.886,0,0,0,0.001,86798336.0,0.0,0.317,1.0,4.871,4.199,3.144,4.859,0,0.002,163254272.0,0.0,0.12,1.0,3.5,2.52,3.5,7.5,0,0.004,17436672.0,0.0,0,0,3.179,2.305,0,0,0.0,3.808,34.966,0.0,3.471,30.526,0.0,3.64,30.25,0.0,3.15,34.638,0.0
9
+ 2026-05-19 11:53:08,0.002,19087360.0,0.0,0.655,1.0,15.751,16.673,18.353,84.333,0,0.0,10526720.0,0.0,0,0,2.619,2.092,0,0,0,0.001,25952256.0,0.0,4.132,1.0,7.54,5.494,0.281,1.386,0,0.015,80773120.0,0.036,0.633,1.0,4.54,3.858,3.507,60.092,0,0.002,50241536.0,0.0,1.556,1.0,6.142,5.433,2.813,4.684,0,0.0,30580736.0,0.0,0,0,2.631,2.075,0,0,0,0.0,11460608.0,0.0,0.333,1.0,3.275,2.525,0.404,4.394,0,0.001,89395200.0,0.0,0,0,2.412,1.886,0,0,0,0.002,86798336.0,0.0,1.018,1.0,5.1,4.685,3.127,4.829,0,0.003,163254272.0,0.0,0.134,1.0,3.694,2.835,3.5,7.5,0,0.004,17436672.0,0.0,0,0,3.841,2.784,0,0,0.0,3.626,34.971,0.0,3.471,30.526,0.0,3.513,30.25,0.0,3.15,34.638,0.0
10
+ 2026-05-19 11:53:13,0.004,19841024.0,0.004,0.7,1.0,11.055,11.159,18.018,74.452,0,0.0,10526720.0,0.0,0,0,2.619,2.092,0,0,0,0.003,27541504.0,0.0,4.133,1.0,4.545,3.48,0.278,0.5,0,0.015,80773120.0,0.036,1.934,1.0,4.54,3.858,3.464,25.791,0,0.004,50720768.0,0.001,4.331,1.0,6.113,5.517,2.7,4.591,0,0.0,30580736.0,0.0,0,0,2.631,2.075,0,0,0,0.0,11460608.0,0.0,1.209,1.0,2.644,2.12,0.359,3.79,0,0.001,89399296.0,0.0,0,0,2.412,1.886,0,0,0,0.002,86798336.0,0.0,1.11,1.0,4.912,4.659,3.076,4.736,0,0.003,163254272.0,0.0,0.71,1.0,3.694,2.835,4.019,9.965,0,0.004,17436672.0,0.0,0,0,3.841,2.784,0,0,0.0,3.626,34.971,0.0,3.638,30.476,0.0,3.513,30.25,0.0,3.101,34.699,0.0
11
+ 2026-05-19 11:53:18,0.004,19841024.0,0.005,3.346,1.0,44.158,46.249,21.788,162.663,0,0.0,10526720.0,0.0,0,0,2.64,2.107,0,0,0,0.003,27541504.0,0.0,21.673,1.0,5.054,3.87,0.32,3.173,0,0.012,80773120.0,0.026,2.067,1.0,10.536,10.466,3.519,139.537,0,0.004,50720768.0,0.001,4.735,1.0,5.29,4.774,3.035,4.959,0,0.0,30580736.0,0.0,0,0,2.556,1.982,0,0,0,0.001,11919360.0,0.0,1.324,1.0,3.159,2.534,0.438,4.223,0,0.001,89399296.0,0.0,0,0,2.434,1.753,0,0,0,0.002,86798336.0,0.0,1.111,1.0,4.912,4.659,4.239,9.56,0,0.007,165064704.0,0.015,0.782,1.0,3.518,2.742,4.139,9.971,0,0.004,17453056.0,0.0,0,0,8.84,6.529,0,0,0.0,3.626,34.971,0.0,3.638,30.476,0.0,3.794,30.267,0.0,3.186,34.699,0.0
12
+ 2026-05-19 11:53:23,0.011,20197376.0,0.004,3.661,1.0,59.004,61.949,22.035,162.275,0,0.0,11325440.0,0.0,0,0,2.549,2.006,0,0,0,0.003,27541504.0,0.0,23.826,1.0,34.852,27.363,0.33,3.369,0,0.023,84770816.0,0.078,2.067,1.0,12.158,12.227,3.518,141.305,0,0.005,50720768.0,0.001,4.844,1.0,21.733,21.315,3.036,4.971,0,0.0,30703616.0,0.0,0,0,2.548,1.943,0,0,0,0.001,11919360.0,0.0,1.378,1.0,6.578,4.458,0.444,4.225,0,0.001,89399296.0,0.0,0,0,2.434,1.753,0,0,0,0.008,87261184.0,0.003,3.837,1.0,4.912,4.659,3.917,9.212,0,0.009,165064704.0,0.021,0.854,1.0,3.518,2.742,4.14,9.943,0,0.004,17453056.0,0.0,0,0,10.184,7.564,0,0,0.0,4.171,34.813,0.0,3.638,30.476,0.0,4.251,30.267,0.0,3.186,34.699,0.0
13
+ 2026-05-19 11:53:28,0.012,20197376.0,0.005,3.778,1.0,59.004,61.949,22.149,158.5,0,0.0,11325440.0,0.0,0,0,2.574,2.035,0,0,0,0.004,27541504.0,0.0,25.844,1.0,34.852,27.363,0.331,3.374,0,0.023,84770816.0,0.078,6.01,1.0,12.158,12.227,3.293,128.854,0,0.004,50720768.0,0.001,12.861,1.0,21.733,21.315,2.335,4.744,0,0.0,30703616.0,0.0,0,0,2.548,1.943,0,0,0,0.001,11919360.0,0.0,2.905,1.0,6.578,4.458,0.318,3.136,0,0.001,89399296.0,0.0,0,0,2.438,1.879,0,0,0,0.008,87261184.0,0.003,4.23,1.0,4.162,3.929,3.923,9.147,0,0.009,165064704.0,0.021,1.741,1.0,5.307,3.735,3.651,9.409,0,0.004,17453056.0,0.0,0,0,10.184,7.564,0,0,0.0,4.171,34.813,0.0,4.018,30.517,0.0,4.251,30.267,0.0,3.243,34.725,0.0
14
+ 2026-05-19 11:53:33,0.012,20197376.0,0.005,7.316,1.0,109.983,118.764,17.859,88.389,0,0.0,11325440.0,0.0,0,0,2.574,2.035,0,0,0,0.009,27525120.0,0.0,45.138,1.0,34.852,27.363,0.294,2.312,0,0.026,84770816.0,0.097,6.575,1.0,13.433,14.267,3.268,76.813,0,0.015,54870016.0,0.002,14.098,1.0,21.733,21.315,2.465,4.641,0,0.0,30846976.0,0.0,0,0,2.25,1.796,0,0,0,0.001,12296192.0,0.0,3.19,1.0,8.042,5.223,0.309,2.96,0,0.001,89399296.0,0.0,0,0,2.438,1.879,0,0,0,0.009,87261184.0,0.004,4.622,1.0,17.046,18.458,3.572,8.34,0,0.007,165064704.0,0.017,1.921,1.0,6.631,4.683,3.466,9.125,0,0.005,17473536.0,0.0,0,0,16.36,11.896,0,0,0.0,4.171,34.813,0.0,4.018,30.517,0.0,4.651,30.261,0.0,3.106,34.725,0.0
15
+ 2026-05-19 11:53:38,0.023,20484096.0,0.004,8.024,1.0,109.983,118.764,17.848,88.351,0,0.0,11476992.0,0.0,0,0,2.594,2.1,0,0,0,0.01,27525120.0,0.0,49.792,1.0,45.545,35.813,0.296,2.412,0,0.032,84770816.0,0.117,6.778,1.0,29.201,29.733,3.246,75.434,0,0.02,54870016.0,0.003,14.844,1.0,47.425,47.206,2.451,4.637,0,0.0,30846976.0,0.0,0,0,2.23,1.831,0,0,0,0.001,12296192.0,0.0,3.422,1.0,8.042,5.223,0.307,2.901,0,0.0,89399296.0,0.0,0,0,1.911,1.528,0,0,0,0.009,87261184.0,0.004,7.007,1.0,22.535,24.966,3.396,7.399,0,0.017,166875136.0,0.034,2.1,1.0,8.369,5.545,3.466,9.109,0,0.005,17473536.0,0.0,0,0,16.36,11.896,0,0,0.0,4.207,34.836,0.0,4.018,30.517,0.0,5.185,30.261,0.0,3.106,34.725,0.0
16
+ 2026-05-19 11:53:43,0.025,20484096.0,0.005,8.489,1.0,176.569,187.114,17.747,87.941,0,0.0,11476992.0,0.0,0,0,1.837,1.49,0,0,0,0.011,27525120.0,0.0,54.446,1.0,35.019,27.536,0.296,2.433,0,0.027,86560768.0,0.081,10.826,1.0,32.488,33.08,2.96,16.444,0,0.02,54870016.0,0.003,25.64,1.0,47.425,47.425,1.77,4.494,0,0.0,30982144.0,0.0,0,0,2.374,1.921,0,0,0,0.002,12972032.0,0.0,4.846,1.0,11.261,6.827,0.292,2.204,0,0.001,89395200.0,0.0,0,0,1.625,1.3,0,0,0,0.013,87261184.0,0.007,7.742,1.0,22.535,24.966,3.399,7.374,0,0.017,166875136.0,0.034,2.993,1.0,8.369,5.545,3.332,7.539,0,0.005,17477632.0,0.0,0,0,16.36,11.896,0,0,0.0,4.207,34.836,0.0,4.444,30.525,0.0,5.185,30.261,0.0,2.996,34.599,0.0
17
+ 2026-05-19 11:53:48,0.027,20484096.0,0.005,12.185,1.0,190.733,204.319,16.408,56.546,0,0.0,11476992.0,0.0,0,0,2.044,1.657,0,0,0,0.015,27611136.0,0.0,72.989,1.0,50.45,38.875,0.282,1.496,0,0.027,86560768.0,0.081,11.866,1.0,39.437,40.156,2.944,4.986,0,0.02,54870016.0,0.003,28.167,1.0,47.425,47.425,1.696,4.441,0,0.0,30982144.0,0.0,0,0,1.718,1.387,0,0,0,0.002,12972032.0,0.0,5.334,1.0,14.881,8.807,0.294,2.347,0,0.001,89395200.0,0.0,0,0,2.681,1.987,0,0,0,0.02,87298048.0,0.004,8.477,1.0,26.729,29.434,3.295,6.345,0,0.023,166875136.0,0.05,3.306,1.0,9.05,5.839,3.24,5.592,0,0.005,17477632.0,0.0,0,0,20.185,14.59,0,0,0.0,4.207,34.836,0.0,4.444,30.525,0.0,5.746,30.339,0.0,3.057,34.599,0.0
18
+ 2026-05-19 11:53:53,0.027,20484096.0,0.001,13.376,1.0,212.907,231.329,16.398,56.308,0,0.0,11546624.0,0.0,0,0,1.985,1.639,0,0,0,0.016,27611136.0,0.0,80.537,1.0,50.45,38.875,0.283,1.584,0,0.033,86560768.0,0.1,12.489,1.0,42.117,42.465,2.928,4.963,0,0.023,54870016.0,0.003,30.333,1.0,74.041,73.909,1.681,4.436,0,0.0,30982144.0,0.0,0,0,2.132,1.722,0,0,0,0.002,12972032.0,0.0,5.821,1.0,14.881,8.807,0.293,2.328,0,0.001,89395200.0,0.0,0,0,2.681,1.987,0,0,0,0.02,87298048.0,0.004,9.943,1.0,26.729,29.434,3.246,5.515,0,0.022,168030208.0,0.033,3.619,1.0,9.861,6.026,3.239,5.548,0,0.005,17477632.0,0.0,0,0,28.63,20.68,0,0,0.0,4.172,34.856,0.0,4.444,30.525,0.0,6.303,30.339,0.0,3.057,34.599,0.0
19
+ 2026-05-19 11:53:58,0.039,20795392.0,0.002,14.289,1.0,227.678,248.623,16.31,53.75,0,0.0,11546624.0,0.0,0,0,1.985,1.639,0,0,0,0.019,27611136.0,0.0,88.085,1.0,110.226,90.078,0.283,1.6,0,0.026,88350720.0,0.067,15.149,1.0,42.117,42.465,2.834,4.878,0,0.038,59838464.0,0.006,39.469,1.0,74.041,74.13,1.198,4.34,0,0.0,30982144.0,0.0,0,0,1.792,1.447,0,0,0,0.002,13082624.0,0.0,6.736,1.0,15.471,9.029,0.288,1.934,0,0.001,89403392.0,0.0,0,0,2.681,1.987,0,0,0,0.02,87298048.0,0.004,10.934,1.0,35.457,38.773,3.245,5.499,0,0.022,168030208.0,0.033,4.287,1.0,11.461,7.004,3.19,4.942,0,0.004,17477632.0,0.0,0,0,28.63,20.68,0,0,0.0,4.172,34.856,0.0,4.724,30.466,0.0,6.303,30.339,0.0,3.064,34.747,0.0
20
+ 2026-05-19 11:54:03,0.042,20795392.0,0.002,16.603,1.0,273.954,296.511,15.803,39.301,0,0.0,11599872.0,0.0,0,0,1.985,1.639,0,0,0,0.021,27521024.0,0.0,99.477,1.0,110.226,90.078,0.277,0.499,0,0.026,88350720.0,0.067,16.244,1.0,47.549,47.319,2.829,4.834,0,0.038,59838464.0,0.006,43.136,1.0,74.041,74.13,0.476,4.241,0,0.0,30982144.0,0.0,0,0,2.198,1.792,0,0,0,0.003,13082624.0,0.0,7.133,1.0,17.075,9.699,0.288,1.963,0,0.001,89403392.0,0.0,0,0,2.531,2.042,0,0,0,0.021,87326720.0,0.0,11.889,1.0,35.457,38.773,3.192,4.946,0,0.023,168603648.0,0.017,4.679,1.0,11.517,6.954,3.151,4.871,0,0.005,17485824.0,0.0,0,0,31.382,22.429,0,0,0.0,4.172,34.856,0.0,4.724,30.466,0.0,6.532,30.416,0.0,2.99,34.747,0.0
21
+ 2026-05-19 11:54:08,0.042,20795392.0,0.002,16.644,1.0,229.861,251.006,15.382,24.849,0,0.0,11599872.0,0.0,0,0,2.671,2.145,0,0,0,0.022,27521024.0,0.0,102.356,1.0,126.401,104.699,0.272,0.49,0,0.016,88350720.0,0.007,16.244,1.0,47.549,47.319,2.77,4.742,0,0.038,59838464.0,0.006,44.0,1.0,72.229,72.515,0.468,4.205,0,0.0,31391744.0,0.0,0,0,2.191,1.845,0,0,0,0.003,13082624.0,0.0,7.133,1.0,17.075,9.699,0.278,1.063,0,0.001,89403392.0,0.0,0,0,2.531,2.042,0,0,0,0.021,87326720.0,0.0,12.333,1.0,22.275,24.0,3.068,4.722,0,0.023,168603648.0,0.017,4.711,1.0,10.4,6.174,3.046,4.683,0,0.005,17485824.0,0.0,0,0,32.876,23.642,0,0,0.0,3.839,34.825,0.0,4.724,30.466,0.0,6.578,30.416,0.0,2.99,34.747,0.0
22
+ 2026-05-19 11:54:13,0.045,20795392.0,0.002,16.644,1.0,288.634,316.914,15.222,24.408,0,0.0,11599872.0,0.0,0,0,2.671,2.145,0,0,0,0.019,27521024.0,0.0,102.356,1.0,126.401,104.699,0.269,0.485,0,0.015,89968640.0,0.005,17.222,1.0,49.282,48.928,2.623,4.587,0,0.044,59838464.0,0.007,53.978,1.0,100.607,100.649,0.417,4.023,0,0.0,31391744.0,0.0,0,0,2.191,1.845,0,0,0,0.002,13082624.0,0.0,7.333,1.0,16.856,9.55,0.276,0.496,0,0.001,89403392.0,0.0,0,0,2.364,1.937,0,0,0,0.021,87326720.0,0.0,12.333,1.0,31.054,33.595,3.022,4.64,0,0.023,168603648.0,0.017,5.089,1.0,12.198,7.242,3.019,4.633,0,0.005,17485824.0,0.0,0,0,32.876,23.642,0,0,0.0,3.839,34.825,0.0,4.788,30.538,0.0,6.578,30.416,0.0,2.944,34.659,0.0
23
+ 2026-05-19 11:54:18,0.046,20963328.0,0.003,17.889,1.0,309.538,339.873,14.834,24.068,0,0.0,11718656.0,0.0,0,0,2.671,2.145,0,0,0,0.024,27623424.0,0.0,111.267,1.0,128.41,106.389,0.266,0.479,0,0.015,89968640.0,0.005,17.222,1.0,50.426,49.903,2.579,4.521,0,0.04,62668800.0,0.005,53.978,1.0,100.607,100.649,0.377,3.832,0,0.0,31391744.0,0.0,0,0,2.729,2.242,0,0,0,0.003,13729792.0,0.0,7.333,1.0,16.856,9.55,0.275,0.495,0,0.001,89403392.0,0.0,0,0,2.34,1.845,0,0,0,0.022,87359488.0,0.0,12.333,1.0,37.948,41.053,3.007,4.613,0,0.017,168976384.0,0.0,5.089,1.0,10.321,6.127,3.0,4.6,0,0.004,17485824.0,0.0,0,0,34.521,24.993,0,0,0.0,3.839,34.825,0.0,4.788,30.538,0.0,6.708,30.403,0.0,2.994,34.659,0.0
24
+ 2026-05-19 11:54:23,0.048,20963328.0,0.004,17.889,1.0,309.538,339.873,14.834,24.068,0,0.0,11718656.0,0.0,0,0,2.118,1.68,0,0,0,0.024,27623424.0,0.0,111.267,1.0,80.287,66.623,0.266,0.478,0,0.013,89968640.0,0.0,17.222,1.0,50.333,49.979,2.579,4.521,0,0.04,62668800.0,0.005,53.978,1.0,107.976,107.686,0.361,3.714,0,0.0,31522816.0,0.0,0,0,2.729,2.242,0,0,0,0.003,13729792.0,0.0,7.333,1.0,16.557,9.366,0.275,0.495,0,0.001,89403392.0,0.0,0,0,2.34,1.845,0,0,0,0.016,87359488.0,0.0,12.289,1.0,32.88,35.571,3.007,4.613,0,0.02,168976384.0,0.0,5.089,1.0,12.698,7.527,3.0,4.6,0,0.005,17485824.0,0.0,0,0,34.33,24.835,0,0,0.0,3.857,34.867,0.0,4.788,30.538,0.0,6.757,30.403,0.0,2.994,34.659,0.0
25
+ 2026-05-19 11:54:28,0.048,21041152.0,0.003,17.889,1.0,251.076,275.682,14.834,24.068,0,0.0,11718656.0,0.0,0,0,2.118,1.68,0,0,0,0.024,27623424.0,0.0,111.267,1.0,91.625,76.031,0.266,0.478,0,0.013,93196288.0,0.0,17.356,1.0,50.333,49.979,2.543,4.511,0,0.04,62668800.0,0.005,60.844,1.0,112.009,111.562,0.329,3.36,0,0.0,31522816.0,0.0,0,0,2.729,2.242,0,0,0,0.003,13729792.0,0.0,7.289,1.0,16.619,9.435,0.276,0.496,0,0.001,89403392.0,0.0,0,0,2.429,2.113,0,0,0,0.018,87375872.0,0.0,12.289,1.0,37.587,40.748,3.007,4.613,0,0.02,168976384.0,0.0,5.111,1.0,12.695,7.474,3.004,4.608,0,0.005,17485824.0,0.0,0,0,34.33,24.835,0,0,0.0,3.857,34.867,0.0,4.842,30.501,0.0,6.757,30.403,0.0,3.064,34.628,0.0
26
+ 2026-05-19 11:54:33,0.048,21041152.0,0.003,17.467,1.0,314.02,347.662,15.01,24.64,0,0.0,11739136.0,0.0,0,0,2.118,1.68,0,0,0,0.02,27623424.0,0.0,111.933,1.0,102.654,85.093,0.265,0.477,0,0.013,93196288.0,0.0,17.356,1.0,50.333,49.979,2.543,4.514,0,0.024,64864256.0,0.001,60.844,1.0,112.009,111.562,0.32,3.195,0,0.0,31522816.0,0.0,0,0,2.793,2.268,0,0,0,0.002,23982080.0,0.0,7.289,1.0,16.619,9.435,0.273,0.492,0,0.001,89403392.0,0.0,0,0,2.844,2.474,0,0,0,0.022,87375872.0,0.0,12.289,1.0,37.368,40.434,3.004,4.606,0,0.021,169480192.0,0.007,5.111,1.0,12.855,7.577,3.009,4.616,0,0.005,17485824.0,0.0,0,0,34.84,25.238,0,0,0.0,3.857,34.867,0.0,4.842,30.501,0.0,6.739,30.305,0.0,3.032,34.628,0.0
27
+ 2026-05-19 11:54:38,0.04,21041152.0,0.002,17.467,1.0,314.02,347.662,15.01,24.64,0,0.0,11739136.0,0.0,0,0,2.171,1.682,0,0,0,0.024,27660288.0,0.0,111.933,1.0,113.968,94.472,0.264,0.476,0,0.013,93147136.0,0.0,17.356,1.0,50.432,50.128,2.543,4.514,0,0.027,64864256.0,0.001,60.844,1.0,116.634,116.069,0.31,2.952,0,0.0,31522816.0,0.0,0,0,2.793,2.268,0,0,0,0.002,23982080.0,0.0,7.289,1.0,16.619,9.435,0.273,0.492,0,0.001,89403392.0,0.0,0,0,2.9,2.528,0,0,0,0.022,87375872.0,0.0,12.067,1.0,36.381,39.41,3.004,4.607,0,0.02,169480192.0,0.01,5.111,1.0,12.977,7.65,3.009,4.616,0,0.005,17485824.0,0.0,0,0,34.84,25.238,0,0,0.0,4.079,34.865,0.067,4.842,30.501,0.0,6.732,30.305,0.0,3.032,34.628,0.0
28
+ 2026-05-19 11:54:43,0.047,21217280.0,0.002,17.467,1.0,299.415,332.924,15.01,24.64,0,0.0,11866112.0,0.0,0,0,3.916,2.962,0,0,0,0.024,27660288.0,0.0,111.933,1.0,128.745,105.751,0.264,0.476,0,0.013,93147136.0,0.0,17.022,1.0,50.432,50.128,2.529,4.513,0,0.033,63827968.0,0.007,63.0,1.0,111.692,111.269,0.309,2.915,0,0.0,31174656.0,0.0,0,0,2.581,2.076,0,0,0,0.002,23982080.0,0.0,6.107,1.0,13.813,7.841,0.275,0.496,0,0.001,89403392.0,0.0,0,0,2.9,2.528,0,0,0,0.022,87384064.0,0.0,12.067,1.0,36.381,39.41,3.004,4.607,0,0.02,169480192.0,0.01,4.978,1.0,12.977,7.65,3.009,4.616,0,0.005,17485824.0,0.0,0,0,34.338,24.901,0,0,0.0,4.079,34.865,0.067,5.732,30.831,0.0,6.732,30.305,0.0,3.038,34.634,0.0
29
+ 2026-05-19 11:54:48,0.047,21217280.0,0.002,16.711,1.0,299.415,332.924,15.714,42.468,0,0.0,11866112.0,0.0,0,0,3.916,2.962,0,0,0,0.024,27660288.0,0.0,109.022,1.0,128.745,105.751,0.27,0.486,0,0.013,93147136.0,0.0,17.022,1.0,50.432,50.128,2.518,4.509,0,0.033,63827968.0,0.007,63.0,1.0,111.692,111.269,0.316,3.116,0,0.0,31174656.0,0.0,0,0,3.7,2.901,0,0,0,0.002,23982080.0,0.0,5.504,1.0,12.434,7.059,0.297,3.94,0,0.001,89403392.0,0.0,0,0,3.051,2.638,0,0,0,0.022,87384064.0,0.0,12.067,1.0,36.006,39.205,3.002,4.603,0,0.017,169480192.0,0.008,4.978,1.0,13.626,8.058,3.009,4.616,0,0.005,17485824.0,0.0,0,0,34.338,24.901,0,0,0.0,4.079,34.865,0.067,5.732,30.831,0.0,6.794,30.042,0.0,3.204,34.634,0.0
30
+ 2026-05-19 11:54:53,0.047,21217280.0,0.002,16.711,1.0,288.108,320.899,15.714,42.468,0,0.0,11866112.0,0.0,0,0,3.362,2.543,0,0,0,0.022,27688960.0,0.0,109.022,1.0,128.745,105.751,0.269,0.485,0,0.012,93405184.0,0.0,17.022,1.0,28.975,28.925,2.518,4.509,0,0.033,63827968.0,0.007,63.0,1.0,110.237,109.805,0.316,3.116,0,0.0,31174656.0,0.0,0,0,3.7,2.901,0,0,0,0.002,23982080.0,0.0,4.901,1.0,16.832,11.278,0.3,4.186,0,0.001,89407488.0,0.0,0,0,3.128,2.665,0,0,0,0.019,87384064.0,0.0,11.378,1.0,36.006,39.205,3.004,4.607,0,0.017,170057728.0,0.008,4.978,1.0,13.527,8.142,3.009,4.616,0,0.005,17620992.0,0.0,0,0,33.643,24.375,0,0,0.0,3.961,34.882,0.0,5.732,30.831,0.0,6.804,30.042,0.0,3.204,34.634,0.0
31
+ 2026-05-19 11:54:58,0.03,21217280.0,0.0,16.711,1.0,272.055,305.907,15.714,42.468,0,0.0,11866112.0,0.0,0,0,3.362,2.543,0,0,0,0.022,27688960.0,0.0,109.022,1.0,106.789,87.425,0.269,0.485,0,0.012,93405184.0,0.0,16.111,1.0,33.693,33.635,2.541,4.513,0,0.025,63983616.0,0.005,64.467,1.0,100.982,100.402,0.341,3.516,0,0.0,31432704.0,0.0,0,0,3.7,2.901,0,0,0,0.079,18923520.0,0.689,4.358,1.0,16.952,11.785,0.304,4.444,0,0.001,89407488.0,0.0,0,0,3.128,2.665,0,0,0,0.017,87384064.0,0.0,11.378,1.0,27.319,29.746,3.004,4.607,0,0.017,170057728.0,0.008,4.444,1.0,13.527,8.142,3.009,4.617,0,0.005,17620992.0,0.0,0,0,28.025,20.305,0,0,0.0,3.961,34.882,0.0,6.529,30.963,0.0,6.804,30.042,0.0,3.326,34.175,0.0
32
+ 2026-05-19 11:55:03,0.042,21479424.0,0.0,15.022,1.0,272.055,305.907,17.577,845.673,0,0.0,12005376.0,0.0,0,0,3.362,2.543,0,0,0,0.021,27688960.0,0.0,100.244,1.0,116.971,94.292,0.285,1.726,0,0.012,93405184.0,0.0,16.111,1.0,45.716,45.331,2.516,4.509,0,0.031,63983616.0,0.006,64.467,1.0,100.982,100.402,0.378,3.833,0,0.0,31432704.0,0.0,0,0,4.078,3.092,0,0,0,0.092,18923520.0,0.807,5.986,1.0,14.418,10.001,0.48,973.072,0,0.001,89407488.0,0.0,0,0,3.525,2.983,0,0,0,0.02,87429120.0,0.0,11.378,1.0,34.005,36.441,3.008,4.614,0,0.016,170057728.0,0.011,4.444,1.0,8.85,5.4,3.01,4.618,0,0.004,17625088.0,0.0,0,0,31.408,22.453,0,0,0.0,3.961,34.882,0.0,6.529,30.963,0.0,6.629,30.012,0.0,3.268,34.175,0.0
33
+ 2026-05-19 11:55:08,0.042,21479424.0,0.0,15.022,1.0,272.055,305.907,17.577,845.673,0,0.0,12005376.0,0.0,0,0,4.397,3.267,0,0,0,0.021,27688960.0,0.0,100.244,1.0,111.213,88.656,0.285,1.729,0,0.01,93405184.0,0.0,16.111,1.0,45.716,45.331,2.515,4.509,0,0.031,63983616.0,0.006,64.467,1.0,100.982,100.402,0.378,3.833,0,0.0,31432704.0,0.0,0,0,3.621,2.833,0,0,0,0.114,19931136.0,0.979,5.859,1.0,15.63,11.85,2.886,985.779,0,0.001,89452544.0,0.0,0,0,2.915,2.467,0,0,0,0.02,87429120.0,0.0,10.378,1.0,34.005,36.441,3.008,4.615,0,0.016,170479616.0,0.012,4.444,1.0,12.262,7.463,3.01,4.618,0,0.005,17625088.0,0.0,0,0,30.487,21.705,0,0,0.0,4.037,34.902,0.0,6.529,30.963,0.0,6.408,30.012,0.0,3.268,34.175,0.0
34
+ 2026-05-19 11:55:13,0.042,11030528.0,0.0,15.022,1.0,167.825,190.625,17.577,845.673,0,0.0,12005376.0,0.0,0,0,3.856,2.897,0,0,0,0.02,27701248.0,0.0,100.244,1.0,110.854,87.806,0.285,1.729,0,0.007,93405184.0,0.0,14.711,1.0,44.51,43.965,2.571,4.523,0,0.03,64241664.0,0.005,61.6,1.0,88.905,88.331,0.411,3.991,0,0.0,31432704.0,0.0,0,0,3.621,2.833,0,0,0,0.128,19931136.0,1.105,3.206,1.0,9.71,8.849,643.904,1272.558,0,0.001,89452544.0,0.0,0,0,2.924,2.401,0,0,0,0.02,87429120.0,0.0,10.378,1.0,33.233,35.269,3.008,4.615,0,0.016,83464192.0,0.012,4.4,1.0,12.262,7.463,3.006,4.617,0,0.005,8904704.0,0.0,0,0,30.487,21.705,0,0,0.0,4.037,34.902,0.0,7.279,30.925,0.0,6.408,30.012,0.0,3.172,34.294,0.0
35
+ 2026-05-19 11:55:18,0.041,11030528.0,0.0,14.711,1.0,243.947,278.778,19.698,986.905,0,0.0,12005376.0,0.0,0,0,3.856,2.897,0,0,0,0.018,27701248.0,0.0,94.2,1.0,104.369,81.406,0.299,2.573,0,0.012,48099328.0,0.0,14.711,1.0,44.654,44.231,2.565,4.525,0,0.029,64241664.0,0.006,61.6,1.0,88.905,88.331,0.465,4.145,0,0.0,31690752.0,0.0,0,0,3.311,2.594,0,0,0,0.142,19931136.0,1.23,3.753,1.0,9.025,8.225,779.681,1700.337,0,0.001,44736512.0,0.0,0,0,2.924,2.401,0,0,0,0.016,87429120.0,0.0,10.378,1.0,33.233,35.269,3.006,4.611,0,0.013,83656704.0,0.004,4.4,1.0,12.31,7.425,3.006,4.617,0,0.005,8904704.0,0.0,0,0,30.769,21.816,0,0,0.0,4.037,34.902,0.0,7.279,30.925,0.0,6.257,29.915,0.0,3.197,34.294,0.0
36
+ 2026-05-19 11:55:23,0.041,11030528.0,0.0,14.711,1.0,243.947,278.778,19.698,986.905,0,0.0,12288000.0,0.0,0,0,2.56,1.954,0,0,0,0.018,19140608.0,0.0,94.2,1.0,104.369,81.406,0.298,2.537,0,0.012,48099328.0,0.0,14.711,1.0,43.669,43.21,2.565,4.525,0,0.029,64241664.0,0.006,61.6,1.0,88.905,88.331,0.465,4.145,0,0.0,31690752.0,0.0,0,0,3.311,2.594,0,0,0,0.162,14061568.0,1.436,4.245,1.0,13.021,12.268,781.566,1704.0,0,0.001,44736512.0,0.0,0,0,2.924,2.401,0,0,0,0.019,87453696.0,0.0,10.333,1.0,33.233,35.269,3.006,4.611,0,0.013,83656704.0,0.004,4.4,1.0,11.992,7.273,3.005,4.617,0,0.005,8773632.0,0.0,0,0,29.306,20.462,0,0,0.0,3.964,34.721,0.467,7.279,30.925,0.0,6.172,29.915,0.0,3.197,34.294,0.0
37
+ 2026-05-19 11:55:28,0.04,11030528.0,0.0,14.711,1.0,243.947,278.778,19.698,986.905,0,0.0,5783552.0,0.0,0,0,2.036,1.554,0,0,0,0.019,19152896.0,0.0,94.2,1.0,89.199,69.574,0.298,2.537,0,0.012,47886336.0,0.0,14.667,1.0,43.876,43.354,2.571,4.526,0,0.029,65097728.0,0.005,65.533,1.0,85.557,84.748,0.474,4.157,0,0.0,15618048.0,0.0,0,0,3.311,2.594,0,0,0,0.177,14061568.0,1.568,4.737,1.0,13.021,12.268,783.258,1707.295,0,0.001,44736512.0,0.0,0,0,2.779,2.118,0,0,0,0.019,87453696.0,0.0,10.333,1.0,33.325,35.06,3.006,4.611,0,0.013,83656704.0,0.004,4.133,1.0,11.992,7.273,3.006,4.618,0,0.005,8773632.0,0.0,0,0,29.306,20.462,0,0,0.0,3.964,34.721,0.467,7.132,30.891,0.0,6.172,29.915,0.0,3.237,34.216,0.0
38
+ 2026-05-19 11:55:33,0.039,11091968.0,0.0,14.356,1.0,237.991,274.583,21.311,1084.783,0,0.0,5783552.0,0.0,0,0,1.823,1.391,0,0,0,0.019,19152896.0,0.0,92.244,1.0,99.101,76.513,0.304,2.746,0,0.012,47886336.0,0.0,14.667,1.0,43.876,43.354,2.561,4.527,0,0.028,31727616.0,0.0,65.533,1.0,86.737,85.675,0.493,4.189,0,0.0,15618048.0,0.0,0,0,2.17,1.812,0,0,0,0.124,14061568.0,1.098,5.978,1.0,13.021,12.268,810.718,1732.394,0,0.001,44736512.0,0.0,0,0,2.779,2.118,0,0,0,0.019,43765760.0,0.0,10.333,1.0,31.964,33.543,3.006,4.612,0,0.011,83968000.0,0.004,4.133,1.0,10.782,6.392,3.012,4.628,0,0.004,8773632.0,0.0,0,0,28.843,20.06,0,0,0.0,3.964,34.721,0.467,7.132,30.891,0.0,5.968,29.957,0.0,3.083,34.216,0.0
39
+ 2026-05-19 11:55:38,0.039,11091968.0,0.0,14.356,1.0,237.991,274.583,21.311,1084.783,0,0.0,5783552.0,0.0,0,0,2.734,2.138,0,0,0,0.019,8585216.0,0.0,92.244,1.0,99.101,76.513,0.303,2.731,0,0.012,47886336.0,0.0,14.667,1.0,32.213,32.033,2.561,4.527,0,0.027,31997952.0,0.0,65.533,1.0,86.737,85.675,0.493,4.189,0,0.0,15880192.0,0.0,0,0,2.17,1.812,0,0,0,0.172,14475264.0,1.547,5.978,1.0,12.171,11.762,809.577,1720.561,0,0.001,44736512.0,0.0,0,0,2.545,1.862,0,0,0,0.019,43765760.0,0.0,10.244,1.0,23.656,24.838,3.004,4.608,0,0.013,83968000.0,0.005,4.133,1.0,10.782,6.392,3.011,4.628,0,0.005,8773632.0,0.0,0,0,28.843,20.06,0,0,0.0,3.913,34.738,0.067,7.132,30.891,0.0,5.829,29.957,0.0,3.083,34.216,0.0
40
+ 2026-05-19 11:55:43,0.04,11091968.0,0.0,14.356,1.0,238.811,275.542,21.311,1084.783,0,0.0,5783552.0,0.0,0,0,2.865,2.269,0,0,0,0.019,8585216.0,0.0,92.244,1.0,101.317,78.493,0.303,2.731,0,0.012,47886336.0,0.0,14.333,1.0,35.775,35.576,2.585,4.532,0,0.027,31997952.0,0.0,66.2,1.0,88.256,87.06,0.484,4.173,0,0.0,15880192.0,0.0,0,0,2.17,1.812,0,0,0,0.2,14475264.0,1.798,5.978,1.0,12.171,11.762,809.577,1720.561,0,0.001,44736512.0,0.0,0,0,2.041,1.494,0,0,0,0.019,43765760.0,0.0,10.244,1.0,26.282,27.595,3.004,4.608,0,0.013,83968000.0,0.005,4.222,1.0,10.782,6.392,3.018,4.638,0,0.005,8773632.0,0.0,0,0,29.623,20.615,0,0,0.0,3.913,34.738,0.067,7.099,30.844,0.0,5.829,29.957,0.0,2.954,34.222,0.0
41
+ 2026-05-19 11:55:48,0.04,10866688.0,0.0,14.667,1.0,238.785,275.692,20.971,969.731,0,0.0,5783552.0,0.0,0,0,2.865,2.269,0,0,0,0.018,8593408.0,0.0,93.044,1.0,100.269,77.659,0.303,2.71,0,0.012,47841280.0,0.0,14.333,1.0,42.747,42.509,2.59,4.533,0,0.027,31997952.0,0.0,66.2,1.0,88.256,87.06,0.488,4.179,0,0.0,15880192.0,0.0,0,0,1.125,0.925,0,0,0,0.199,14729216.0,1.789,6.133,1.0,12.171,11.762,796.574,1544.828,0,0.001,44736512.0,0.0,0,0,2.586,1.935,0,0,0,0.019,43790336.0,0.0,10.244,1.0,31.925,33.67,3.002,4.604,0,0.015,84312064.0,0.008,4.222,1.0,10.843,6.462,3.022,4.647,0,0.005,8781824.0,0.0,0,0,24.909,17.335,0,0,0.0,3.913,34.738,0.067,7.099,30.844,0.0,5.892,29.953,0.0,3.019,34.222,0.0
42
+ 2026-05-19 11:55:53,0.04,10866688.0,0.0,14.667,1.0,238.785,275.692,20.971,969.731,0,0.0,5783552.0,0.0,0,0,2.923,2.339,0,0,0,0.018,8593408.0,0.0,93.044,1.0,100.269,77.659,0.303,2.7,0,0.008,47841280.0,0.0,14.333,1.0,42.806,42.434,2.59,4.533,0,0.022,31997952.0,0.0,66.2,1.0,88.256,87.06,0.488,4.179,0,0.0,16048128.0,0.0,0,0,1.262,1.038,0,0,0,0.199,14729216.0,1.789,6.133,1.0,10.102,9.812,796.574,1544.828,0,0.001,44736512.0,0.0,0,0,2.632,1.924,0,0,0,0.019,43790336.0,0.0,10.422,1.0,31.925,33.67,3.002,4.604,0,0.015,84312064.0,0.006,4.222,1.0,11.04,6.546,3.022,4.647,0,0.005,8781824.0,0.0,0,0,29.044,20.306,0,0,0.0,3.821,34.714,0.0,7.099,30.844,0.0,5.953,29.953,0.0,3.019,34.222,0.0
43
+ 2026-05-19 11:55:58,0.04,10866688.0,0.0,14.667,1.0,235.54,271.947,20.971,969.731,0,0.0,5795840.0,0.0,0,0,2.745,2.183,0,0,0,0.018,8593408.0,0.0,93.044,1.0,98.916,76.281,0.303,2.7,0,0.009,47841280.0,0.0,14.511,1.0,42.806,42.434,2.586,4.529,0,0.027,35627008.0,0.0,69.778,1.0,86.754,85.504,0.482,4.168,0,0.0,16048128.0,0.0,0,0,2.245,1.76,0,0,0,0.199,14729216.0,1.833,6.133,1.0,12.051,11.749,796.574,1544.828,0,0.001,44736512.0,0.0,0,0,2.632,1.924,0,0,0,0.019,43790336.0,0.0,10.422,1.0,31.925,33.67,3.002,4.604,0,0.014,84201472.0,0.004,3.933,1.0,11.04,6.546,3.022,4.64,0,0.005,8781824.0,0.0,0,0,29.044,20.306,0,0,0.0,3.821,34.714,0.0,7.078,30.86,0.0,5.953,29.953,0.0,3.072,34.239,0.0
44
+ 2026-05-19 11:56:03,0.039,10866688.0,0.0,14.067,1.0,235.54,271.947,21.871,944.792,0,0.0,5795840.0,0.0,0,0,2.745,2.183,0,0,0,0.018,8474624.0,0.0,95.111,1.0,95.692,73.626,0.309,2.917,0,0.009,47841280.0,0.0,14.511,1.0,41.891,41.416,2.577,4.524,0,0.027,35627008.0,0.0,69.778,1.0,86.754,85.504,0.492,4.19,0,0.0,16048128.0,0.0,0,0,2.245,1.76,0,0,0,0.171,14729216.0,1.569,6.333,1.0,12.051,11.749,780.933,1137.705,0,0.001,44736512.0,0.0,0,0,2.647,2.046,0,0,0,0.019,43790336.0,0.0,10.422,1.0,31.099,33.113,3.004,4.608,0,0.014,84201472.0,0.004,3.933,1.0,10.943,6.548,3.017,4.631,0,0.004,8781824.0,0.0,0,0,27.932,19.487,0,0,0.0,3.821,34.714,0.0,7.078,30.86,0.0,5.987,30.042,0.0,2.997,34.239,0.0
45
+ 2026-05-19 11:56:08,0.03,10866688.0,0.0,14.067,1.0,235.54,271.947,21.871,944.792,0,0.0,5795840.0,0.0,0,0,2.745,2.183,0,0,0,0.018,8474624.0,0.0,95.111,1.0,95.692,73.626,0.311,2.964,0,0.012,48373760.0,0.0,14.511,1.0,35.705,35.301,2.577,4.524,0,0.027,35627008.0,0.0,69.778,1.0,86.754,85.504,0.492,4.19,0,0.0,16158720.0,0.0,0,0,2.646,2.117,0,0,0,0.199,14839808.0,1.812,6.333,1.0,11.985,11.566,780.933,1137.705,0,0.001,44736512.0,0.0,0,0,2.647,2.046,0,0,0,0.015,43790336.0,0.0,10.489,1.0,31.099,33.113,3.004,4.608,0,0.014,84201472.0,0.005,3.933,1.0,10.588,6.384,3.017,4.631,0,0.005,8781824.0,0.0,0,0,28.398,19.999,0,0,0.0,3.729,34.752,0.067,7.078,30.86,0.0,5.987,30.042,0.0,2.997,34.239,0.0
46
+ 2026-05-19 11:56:13,0.027,10866688.0,0.0,14.067,1.0,241.346,278.236,21.871,944.792,0,0.0,5795840.0,0.0,0,0,1.622,1.348,0,0,0,0.017,8474624.0,0.0,95.111,1.0,63.5,48.675,0.311,2.964,0,0.012,48373760.0,0.0,14.333,1.0,32.214,31.849,2.582,4.525,0,0.028,34476032.0,0.007,70.178,1.0,48.75,48.15,0.492,4.194,0,0.0,16158720.0,0.0,0,0,2.646,2.117,0,0,0,0.199,14839808.0,1.812,6.333,1.0,9.554,9.22,780.933,1137.705,0,0.001,44736512.0,0.0,0,0,2.436,2.013,0,0,0,0.013,43790336.0,0.0,10.489,1.0,25.988,27.998,3.004,4.608,0,0.012,84201472.0,0.005,4.133,1.0,10.588,6.384,3.017,4.63,0,0.005,8781824.0,0.0,0,0,28.398,19.999,0,0,0.0,3.729,34.752,0.067,7.193,30.806,0.0,5.987,30.042,0.0,2.904,34.305,0.0
47
+ 2026-05-19 11:56:18,0.04,11059200.0,0.0,14.867,1.0,244.688,281.986,21.934,955.328,0,0.0,5812224.0,0.0,0,0,2.09,1.737,0,0,0,0.018,8609792.0,0.0,97.511,1.0,97.707,75.244,0.319,3.161,0,0.012,48373760.0,0.0,14.333,1.0,42.533,42.141,2.586,4.523,0,0.028,34476032.0,0.007,70.178,1.0,91.799,90.293,1.089,4.226,0,0.0,15663104.0,0.0,0,0,2.774,2.132,0,0,0,0.199,14839808.0,1.812,6.4,1.0,12.406,11.936,788.0,1363.158,0,0.001,44732416.0,0.0,0,0,2.436,2.013,0,0,0,0.019,43802624.0,0.0,10.489,1.0,32.568,35.086,3.006,4.612,0,0.016,84307968.0,0.012,4.133,1.0,10.918,6.57,3.011,4.62,0,0.006,8781824.0,0.001,0,0,29.388,21.14,0,0,0.0,3.729,34.752,0.067,7.193,30.806,0.0,6.025,30.031,0.0,2.935,34.305,0.0
48
+ 2026-05-19 11:56:23,0.04,11059200.0,0.0,14.867,1.0,244.688,281.986,21.934,955.328,0,0.0,5812224.0,0.0,0,0,2.09,1.737,0,0,0,0.018,8609792.0,0.0,97.511,1.0,97.707,75.244,0.32,3.18,0,0.012,49352704.0,0.0,14.333,1.0,42.533,42.141,2.586,4.523,0,0.028,34476032.0,0.007,70.178,1.0,91.799,90.293,1.089,4.226,0,0.0,15663104.0,0.0,0,0,2.774,2.132,0,0,0,0.198,14868480.0,1.788,6.4,1.0,12.379,11.99,788.0,1363.158,0,0.001,44732416.0,0.0,0,0,2.436,2.013,0,0,0,0.02,43802624.0,0.0,10.578,1.0,32.568,35.086,3.006,4.612,0,0.016,84307968.0,0.012,4.133,1.0,10.918,6.57,3.011,4.62,0,0.006,8781824.0,0.001,0,0,29.388,21.14,0,0,0.0,3.789,34.73,0.0,7.193,30.806,0.0,6.075,30.031,0.0,2.935,34.305,0.0
49
+ 2026-05-19 11:56:28,0.04,11059200.0,0.0,14.867,1.0,246.424,284.035,21.934,955.328,0,0.0,5812224.0,0.0,0,0,2.09,1.737,0,0,0,0.019,8609792.0,0.0,97.511,1.0,97.707,75.244,0.32,3.18,0,0.013,49352704.0,0.0,14.844,1.0,43.988,43.443,2.58,4.522,0,0.024,34476032.0,0.008,73.022,1.0,92.501,91.286,1.052,4.218,0,0.0,15663104.0,0.0,0,0,2.774,2.132,0,0,0,0.198,14868480.0,1.788,6.4,1.0,12.379,11.99,788.0,1363.158,0,0.001,44732416.0,0.0,0,0,1.957,1.715,0,0,0,0.019,43810816.0,0.0,10.578,1.0,32.32,34.764,3.006,4.612,0,0.016,84307968.0,0.012,4.222,1.0,10.918,6.57,3.005,4.618,0,0.006,8781824.0,0.001,0,0,29.388,21.14,0,0,0.0,3.789,34.73,0.0,7.215,30.905,0.4,6.075,30.031,0.0,3.01,34.336,0.0
50
+ 2026-05-19 11:56:33,0.041,11149312.0,0.0,14.778,1.0,248.728,286.396,21.613,979.221,0,0.0,5812224.0,0.0,0,0,1.697,1.41,0,0,0,0.019,8609792.0,0.0,100.133,1.0,98.769,75.988,0.319,3.148,0,0.013,49352704.0,0.0,14.844,1.0,43.988,43.443,2.586,4.523,0,0.029,34734080.0,0.006,73.022,1.0,94.002,92.823,0.498,4.204,0,0.0,15790080.0,0.0,0,0,1.865,1.501,0,0,0,0.198,14868480.0,1.788,6.489,1.0,12.379,11.99,794.388,1505.172,0,0.001,44732416.0,0.0,0,0,2.334,2.045,0,0,0,0.02,43810816.0,0.0,10.578,1.0,32.143,34.699,3.004,4.608,0,0.013,84418560.0,0.007,4.222,1.0,8.573,5.144,3.005,4.618,0,0.006,8777728.0,0.001,0,0,30.223,21.984,0,0,0.0,3.789,34.73,0.0,7.215,30.905,0.4,6.051,29.975,0.0,2.958,34.336,0.0
51
+ 2026-05-19 11:56:38,0.041,11149312.0,0.0,14.778,1.0,248.728,286.396,21.613,979.221,0,0.0,5812224.0,0.0,0,0,1.211,1.09,0,0,0,0.019,8650752.0,0.0,100.133,1.0,98.769,75.988,0.318,3.139,0,0.013,49352704.0,0.0,14.844,1.0,43.608,43.336,2.586,4.523,0,0.03,34734080.0,0.008,73.022,1.0,94.002,92.823,0.498,4.204,0,0.0,15790080.0,0.0,0,0,2.07,1.666,0,0,0,0.199,14864384.0,1.822,6.489,1.0,12.821,12.109,794.388,1505.172,0,0.001,44732416.0,0.0,0,0,2.334,2.045,0,0,0,0.02,43823104.0,0.0,10.889,1.0,32.143,34.699,3.004,4.607,0,0.013,84418560.0,0.007,4.222,1.0,7.668,4.601,3.005,4.618,0,0.006,8777728.0,0.001,0,0,29.516,21.42,0,0,0.0,3.761,34.737,0.0,7.215,30.905,0.4,6.099,29.975,0.0,2.958,34.336,0.0
52
+ 2026-05-19 11:56:43,0.041,11149312.0,0.0,14.778,1.0,203.247,234.028,21.613,979.221,0,0.0,5812224.0,0.0,0,0,2.317,1.973,0,0,0,0.019,8650752.0,0.0,100.133,1.0,98.769,75.988,0.318,3.139,0,0.01,49352704.0,0.0,15.022,1.0,43.608,43.336,2.58,4.522,0,0.03,34734080.0,0.008,74.244,1.0,97.624,96.293,0.485,4.182,0,0.0,15790080.0,0.0,0,0,2.119,1.705,0,0,0,0.199,14864384.0,1.822,6.489,1.0,12.821,12.109,794.388,1505.172,0,0.001,44732416.0,0.0,0,0,1.948,1.707,0,0,0,0.02,43823104.0,0.0,10.889,1.0,31.973,34.565,3.004,4.607,0,0.013,84418560.0,0.007,4.444,1.0,11.073,6.563,3.005,4.627,0,0.006,8777728.0,0.001,0,0,29.516,21.42,0,0,0.0,3.761,34.737,0.0,7.172,30.913,0.067,6.099,29.975,0.0,2.899,34.234,0.0
53
+ 2026-05-19 11:56:48,0.018,11149312.0,0.0,15.289,1.0,253.885,291.675,20.944,993.665,0,0.0,5812224.0,0.0,0,0,2.317,1.973,0,0,0,0.02,8650752.0,0.0,98.444,1.0,81.44,62.986,0.311,2.953,0,0.013,49479680.0,0.0,15.022,1.0,43.608,43.336,2.583,4.519,0,0.03,35209216.0,0.006,74.244,1.0,97.914,96.583,0.472,4.153,0,0.0,15790080.0,0.0,0,0,1.914,1.54,0,0,0,0.199,14864384.0,1.831,6.378,1.0,12.821,12.109,801.778,1625.758,0,0.001,44732416.0,0.0,0,0,2.33,1.82,0,0,0,0.013,43823104.0,0.0,10.889,1.0,32.171,34.667,3.002,4.604,0,0.011,84418560.0,0.008,4.444,1.0,11.222,6.565,3.01,4.636,0,0.006,8777728.0,0.002,0,0,29.516,21.42,0,0,0.0,3.761,34.737,0.0,7.172,30.913,0.067,6.135,29.996,0.0,3.072,34.234,0.0
54
+ 2026-05-19 11:56:53,0.018,11149312.0,0.0,15.289,1.0,253.885,291.675,20.944,993.665,0,0.0,5812224.0,0.0,0,0,2.317,1.973,0,0,0,0.02,8650752.0,0.0,98.444,1.0,73.05,56.498,0.309,2.917,0,0.013,49479680.0,0.0,15.022,1.0,42.366,42.264,2.583,4.519,0,0.03,35209216.0,0.006,74.244,1.0,97.914,96.583,0.472,4.153,0,0.0,15790080.0,0.0,0,0,1.709,1.375,0,0,0,0.199,14864384.0,1.831,6.378,1.0,12.821,12.109,801.778,1625.758,0,0.0,44732416.0,0.0,0,0,2.33,1.82,0,0,0,0.011,43823104.0,0.0,10.578,1.0,32.171,34.667,3.004,4.607,0,0.01,84418560.0,0.007,4.444,1.0,11.222,6.565,3.01,4.636,0,0.005,8777728.0,0.001,0,0,29.552,21.546,0,0,0.0,3.7,34.717,0.0,7.172,30.913,0.067,6.136,29.996,0.0,3.072,34.234,0.0
benchmark/boutique/codedefect/86/tool_cache.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/boutique/codedefect/87/code/adservice/src/main/java/hipstershop/AdService.java ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2018, Google LLC.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ package hipstershop;
18
+
19
+ import com.google.common.collect.ImmutableListMultimap;
20
+ import com.google.common.collect.ImmutableMap;
21
+ import com.google.common.collect.Iterables;
22
+ import hipstershop.Demo.Ad;
23
+ import hipstershop.Demo.AdRequest;
24
+ import hipstershop.Demo.AdResponse;
25
+ import io.grpc.Server;
26
+ import io.grpc.ServerBuilder;
27
+ import io.grpc.StatusRuntimeException;
28
+ import io.grpc.health.v1.HealthCheckResponse.ServingStatus;
29
+ import io.grpc.services.*;
30
+ import io.grpc.stub.StreamObserver;
31
+ import java.io.IOException;
32
+ import java.util.ArrayList;
33
+ import java.util.Collection;
34
+ import java.util.List;
35
+ import java.util.Random;
36
+ import java.util.concurrent.TimeUnit;
37
+ import org.apache.logging.log4j.Level;
38
+ import org.apache.logging.log4j.LogManager;
39
+ import org.apache.logging.log4j.Logger;
40
+
41
+ public final class AdService {
42
+
43
+ private static final Logger logger = LogManager.getLogger(AdService.class);
44
+
45
+ @SuppressWarnings("FieldCanBeLocal")
46
+ private static int MAX_ADS_TO_SERVE = 2;
47
+
48
+ private Server server;
49
+ private HealthStatusManager healthMgr;
50
+
51
+ private static final AdService service = new AdService();
52
+
53
+ private void start() throws IOException {
54
+ int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "9555"));
55
+ healthMgr = new HealthStatusManager();
56
+
57
+ server =
58
+ ServerBuilder.forPort(port)
59
+ .addService(new AdServiceImpl())
60
+ .addService(healthMgr.getHealthService())
61
+ .build()
62
+ .start();
63
+ logger.info("Ad Service started, listening on " + port);
64
+ Runtime.getRuntime()
65
+ .addShutdownHook(
66
+ new Thread(
67
+ () -> {
68
+ // Use stderr here since the logger may have been reset by its JVM shutdown hook.
69
+ System.err.println(
70
+ "*** shutting down gRPC ads server since JVM is shutting down");
71
+ AdService.this.stop();
72
+ System.err.println("*** server shut down");
73
+ }));
74
+ healthMgr.setStatus("", ServingStatus.SERVING);
75
+ }
76
+
77
+ private void stop() {
78
+ if (server != null) {
79
+ healthMgr.clearStatus("");
80
+ server.shutdown();
81
+ }
82
+ }
83
+
84
+ private static class AdServiceImpl extends hipstershop.AdServiceGrpc.AdServiceImplBase {
85
+
86
+ /**
87
+ * Retrieves ads based on context provided in the request {@code AdRequest}.
88
+ *
89
+ * @param req the request containing context.
90
+ * @param responseObserver the stream observer which gets notified with the value of {@code
91
+ * AdResponse}
92
+ */
93
+ @Override
94
+ public void getAds(AdRequest req, StreamObserver<AdResponse> responseObserver) {
95
+ AdService service = AdService.getInstance();
96
+ try {
97
+ List<Ad> allAds = new ArrayList<>();
98
+ logger.info("received ad request (context_words=" + req.getContextKeysList() + ")");
99
+ if (req.getContextKeysCount() > 0) {
100
+ for (int i = 0; i < req.getContextKeysCount(); i++) {
101
+ Collection<Ad> ads = service.getAdsByCategory(req.getContextKeys(i));
102
+ allAds.addAll(ads);
103
+ }
104
+ } else {
105
+ allAds = service.getRandomAds();
106
+ }
107
+ if (allAds.isEmpty()) {
108
+ // Serve random ads.
109
+ allAds = service.getRandomAds();
110
+ }
111
+ AdResponse reply = AdResponse.newBuilder().addAllAds(allAds).build();
112
+ responseObserver.onNext(reply);
113
+ responseObserver.onCompleted();
114
+ } catch (StatusRuntimeException e) {
115
+ logger.log(Level.WARN, "GetAds Failed with status {}", e.getStatus());
116
+ responseObserver.onError(e);
117
+ }
118
+ }
119
+ }
120
+
121
+ private static final ImmutableListMultimap<String, Ad> adsMap = createAdsMap();
122
+
123
+ private Collection<Ad> getAdsByCategory(String category) {
124
+ return adsMap.get(category);
125
+ }
126
+
127
+ private static final Random random = new Random();
128
+
129
+ private List<Ad> getRandomAds() {
130
+ List<Ad> ads = new ArrayList<>(MAX_ADS_TO_SERVE);
131
+ Collection<Ad> allAds = adsMap.values();
132
+ for (int i = 0; i < MAX_ADS_TO_SERVE; i++) {
133
+ ads.add(Iterables.get(allAds, random.nextInt(allAds.size())));
134
+ }
135
+ return ads;
136
+ }
137
+
138
+ private static AdService getInstance() {
139
+ return service;
140
+ }
141
+
142
+ /** Await termination on the main thread since the grpc library uses daemon threads. */
143
+ private void blockUntilShutdown() throws InterruptedException {
144
+ if (server != null) {
145
+ server.awaitTermination();
146
+ }
147
+ }
148
+
149
+ private static ImmutableListMultimap<String, Ad> createAdsMap() {
150
+ Ad hairdryer =
151
+ Ad.newBuilder()
152
+ .setRedirectUrl("/product/2ZYFJ3GM2N")
153
+ .setText("Hairdryer for sale. 50% off.")
154
+ .build();
155
+ Ad tankTop =
156
+ Ad.newBuilder()
157
+ .setRedirectUrl("/product/66VCHSJNUP")
158
+ .setText("Tank top for sale. 20% off.")
159
+ .build();
160
+ Ad candleHolder =
161
+ Ad.newBuilder()
162
+ .setRedirectUrl("/product/0PUK6V6EV0")
163
+ .setText("Candle holder for sale. 30% off.")
164
+ .build();
165
+ Ad bambooGlassJar =
166
+ Ad.newBuilder()
167
+ .setRedirectUrl("/product/9SIQT8TOJO")
168
+ .setText("Bamboo glass jar for sale. 10% off.")
169
+ .build();
170
+ Ad watch =
171
+ Ad.newBuilder()
172
+ .setRedirectUrl("/product/1YMWWN1N4O")
173
+ .setText("Watch for sale. Buy one, get second kit for free")
174
+ .build();
175
+ Ad mug =
176
+ Ad.newBuilder()
177
+ .setRedirectUrl("/product/6E92ZMYYFZ")
178
+ .setText("Mug for sale. Buy two, get third one for free")
179
+ .build();
180
+ Ad loafers =
181
+ Ad.newBuilder()
182
+ .setRedirectUrl("/product/L9ECAV7KIM")
183
+ .setText("Loafers for sale. Buy one, get second one for free")
184
+ .build();
185
+ return ImmutableListMultimap.<String, Ad>builder()
186
+ .putAll("clothing", tankTop)
187
+ .putAll("accessories", watch)
188
+ .putAll("footwear", loafers)
189
+ .putAll("hair", hairdryer)
190
+ .putAll("decor", candleHolder)
191
+ .putAll("kitchen", bambooGlassJar, mug)
192
+ .build();
193
+ }
194
+
195
+ private static void initStats() {
196
+ if (System.getenv("DISABLE_STATS") != null) {
197
+ logger.info("Stats disabled.");
198
+ return;
199
+ }
200
+ logger.info("Stats enabled, but temporarily unavailable");
201
+
202
+ long sleepTime = 10; /* seconds */
203
+ int maxAttempts = 5;
204
+
205
+ // TODO(arbrown) Implement OpenTelemetry stats
206
+
207
+ }
208
+
209
+ private static void initTracing() {
210
+ if (System.getenv("DISABLE_TRACING") != null) {
211
+ logger.info("Tracing disabled.");
212
+ return;
213
+ }
214
+ logger.info("Tracing enabled but temporarily unavailable");
215
+ logger.info("See https://github.com/GoogleCloudPlatform/microservices-demo/issues/422 for more info.");
216
+
217
+ // TODO(arbrown) Implement OpenTelemetry tracing
218
+
219
+ logger.info("Tracing enabled - Stackdriver exporter initialized.");
220
+ }
221
+
222
+ /** Main launches the server from the command line. */
223
+ public static void main(String[] args) throws IOException, InterruptedException {
224
+
225
+ new Thread(
226
+ () -> {
227
+ initStats();
228
+ initTracing();
229
+ })
230
+ .start();
231
+
232
+ // Start the RPC server. You shouldn't see any output from gRPC before this.
233
+ logger.info("AdService starting.");
234
+ final AdService service = AdService.getInstance();
235
+ service.start();
236
+ service.blockUntilShutdown();
237
+ }
238
+ }
benchmark/boutique/codedefect/87/code/adservice/src/main/java/hipstershop/AdServiceClient.java ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2018, Google LLC.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ package hipstershop;
18
+
19
+ import hipstershop.Demo.Ad;
20
+ import hipstershop.Demo.AdRequest;
21
+ import hipstershop.Demo.AdResponse;
22
+ import io.grpc.ManagedChannel;
23
+ import io.grpc.ManagedChannelBuilder;
24
+ import io.grpc.StatusRuntimeException;
25
+ import java.util.concurrent.TimeUnit;
26
+ import javax.annotation.Nullable;
27
+ import org.apache.logging.log4j.Level;
28
+ import org.apache.logging.log4j.LogManager;
29
+ import org.apache.logging.log4j.Logger;
30
+
31
+ /** A simple client that requests ads from the Ads Service. */
32
+ public class AdServiceClient {
33
+
34
+ private static final Logger logger = LogManager.getLogger(AdServiceClient.class);
35
+
36
+ private final ManagedChannel channel;
37
+ private final hipstershop.AdServiceGrpc.AdServiceBlockingStub blockingStub;
38
+
39
+ /** Construct client connecting to Ad Service at {@code host:port}. */
40
+ private AdServiceClient(String host, int port) {
41
+ this(
42
+ ManagedChannelBuilder.forAddress(host, port)
43
+ // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
44
+ // needing certificates.
45
+ .usePlaintext()
46
+ .build());
47
+ }
48
+
49
+ /** Construct client for accessing RouteGuide server using the existing channel. */
50
+ private AdServiceClient(ManagedChannel channel) {
51
+ this.channel = channel;
52
+ blockingStub = hipstershop.AdServiceGrpc.newBlockingStub(channel);
53
+ }
54
+
55
+ private void shutdown() throws InterruptedException {
56
+ channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
57
+ }
58
+
59
+ /** Get Ads from Server. */
60
+ public void getAds(String contextKey) {
61
+ logger.info("Get Ads with context " + contextKey + " ...");
62
+ AdRequest request = AdRequest.newBuilder().addContextKeys(contextKey).build();
63
+ AdResponse response;
64
+
65
+ try {
66
+ response = blockingStub.getAds(request);
67
+ } catch (StatusRuntimeException e) {
68
+ logger.log(Level.WARN, "RPC failed: " + e.getStatus());
69
+ return;
70
+ }
71
+ for (Ad ads : response.getAdsList()) {
72
+ logger.info("Ads: " + ads.getText());
73
+ }
74
+ }
75
+
76
+ private static int getPortOrDefaultFromArgs(String[] args) {
77
+ int portNumber = 9555;
78
+ if (2 < args.length) {
79
+ try {
80
+ portNumber = Integer.parseInt(args[2]);
81
+ } catch (NumberFormatException e) {
82
+ logger.warn(String.format("Port %s is invalid, use default port %d.", args[2], 9555));
83
+ }
84
+ }
85
+ return portNumber;
86
+ }
87
+
88
+ private static String getStringOrDefaultFromArgs(
89
+ String[] args, int index, @Nullable String defaultString) {
90
+ String s = defaultString;
91
+ if (index < args.length) {
92
+ s = args[index];
93
+ }
94
+ return s;
95
+ }
96
+
97
+ /**
98
+ * Ads Service Client main. If provided, the first element of {@code args} is the context key to
99
+ * get the ads from the Ads Service
100
+ */
101
+ public static void main(String[] args) throws InterruptedException {
102
+ // Add final keyword to pass checkStyle.
103
+ final String contextKeys = getStringOrDefaultFromArgs(args, 0, "camera");
104
+ final String host = getStringOrDefaultFromArgs(args, 1, "localhost");
105
+ final int serverPort = getPortOrDefaultFromArgs(args);
106
+
107
+ AdServiceClient client = new AdServiceClient(host, serverPort);
108
+ try {
109
+ client.getAds(contextKeys);
110
+ } finally {
111
+ client.shutdown();
112
+ }
113
+
114
+ logger.info("Exiting AdServiceClient...");
115
+ }
116
+ }
benchmark/boutique/codedefect/87/code/cartservice/src/Program.cs ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using Microsoft.AspNetCore.Hosting;
16
+ using Microsoft.Extensions.Hosting;
17
+ using cartservice;
18
+
19
+ CreateHostBuilder(args).Build().Run();
20
+
21
+ static IHostBuilder CreateHostBuilder(string[] args) =>
22
+ Host.CreateDefaultBuilder(args)
23
+ .ConfigureWebHostDefaults(webBuilder =>
24
+ {
25
+ webBuilder.UseStartup<Startup>();
26
+ });
benchmark/boutique/codedefect/87/code/cartservice/src/Startup.cs ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+ using Microsoft.AspNetCore.Builder;
3
+ using Microsoft.AspNetCore.Diagnostics.HealthChecks;
4
+ using Microsoft.AspNetCore.Hosting;
5
+ using Microsoft.AspNetCore.Http;
6
+ using Microsoft.Extensions.Configuration;
7
+ using Microsoft.Extensions.DependencyInjection;
8
+ using Microsoft.Extensions.Diagnostics.HealthChecks;
9
+ using Microsoft.Extensions.Hosting;
10
+ using cartservice.cartstore;
11
+ using cartservice.services;
12
+ using Microsoft.Extensions.Caching.StackExchangeRedis;
13
+
14
+ namespace cartservice
15
+ {
16
+ public class Startup
17
+ {
18
+ public Startup(IConfiguration configuration)
19
+ {
20
+ Configuration = configuration;
21
+ }
22
+
23
+ public IConfiguration Configuration { get; }
24
+
25
+ // This method gets called by the runtime. Use this method to add services to the container.
26
+ // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
27
+ public void ConfigureServices(IServiceCollection services)
28
+ {
29
+ string redisAddress = Configuration["REDIS_ADDR"];
30
+ string spannerProjectId = Configuration["SPANNER_PROJECT"];
31
+ string spannerConnectionString = Configuration["SPANNER_CONNECTION_STRING"];
32
+ string alloyDBConnectionString = Configuration["ALLOYDB_PRIMARY_IP"];
33
+
34
+ if (!string.IsNullOrEmpty(redisAddress))
35
+ {
36
+ services.AddStackExchangeRedisCache(options =>
37
+ {
38
+ options.Configuration = redisAddress;
39
+ });
40
+ services.AddSingleton<ICartStore, RedisCartStore>();
41
+ }
42
+ else if (!string.IsNullOrEmpty(spannerProjectId) || !string.IsNullOrEmpty(spannerConnectionString))
43
+ {
44
+ services.AddSingleton<ICartStore, SpannerCartStore>();
45
+ }
46
+ else if (!string.IsNullOrEmpty(alloyDBConnectionString))
47
+ {
48
+ Console.WriteLine("Creating AlloyDB cart store");
49
+ services.AddSingleton<ICartStore, AlloyDBCartStore>();
50
+ }
51
+ else
52
+ {
53
+ Console.WriteLine("Redis cache host(hostname+port) was not specified. Starting a cart service using in memory store");
54
+ services.AddDistributedMemoryCache();
55
+ services.AddSingleton<ICartStore, RedisCartStore>();
56
+ }
57
+
58
+
59
+ services.AddGrpc();
60
+ }
61
+
62
+ // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
63
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
64
+ {
65
+ if (env.IsDevelopment())
66
+ {
67
+ app.UseDeveloperExceptionPage();
68
+ }
69
+
70
+ app.UseRouting();
71
+
72
+ app.UseEndpoints(endpoints =>
73
+ {
74
+ endpoints.MapGrpcService<CartService>();
75
+ endpoints.MapGrpcService<cartservice.services.HealthCheckService>();
76
+
77
+ endpoints.MapGet("/", async context =>
78
+ {
79
+ await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
80
+ });
81
+ });
82
+ }
83
+ }
84
+ }
benchmark/boutique/codedefect/87/code/cartservice/src/cartstore/AlloyDBCartStore.cs ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using Grpc.Core;
17
+ using Npgsql;
18
+ using Microsoft.Extensions.Configuration;
19
+ using System.Threading.Tasks;
20
+ using Google.Api.Gax.ResourceNames;
21
+ using Google.Cloud.SecretManager.V1;
22
+
23
+ namespace cartservice.cartstore
24
+ {
25
+ public class AlloyDBCartStore : ICartStore
26
+ {
27
+ private readonly string tableName;
28
+ private readonly string connectionString;
29
+
30
+ public AlloyDBCartStore(IConfiguration configuration)
31
+ {
32
+ // Create a Cloud Secrets client.
33
+ SecretManagerServiceClient client = SecretManagerServiceClient.Create();
34
+ var projectId = configuration["PROJECT_ID"];
35
+ var secretId = configuration["ALLOYDB_SECRET_NAME"];
36
+ SecretVersionName secretVersionName = new SecretVersionName(projectId, secretId, "latest");
37
+
38
+ AccessSecretVersionResponse result = client.AccessSecretVersion(secretVersionName);
39
+ // Convert the payload to a string. Payloads are bytes by default.
40
+ string alloyDBPassword = result.Payload.Data.ToStringUtf8().TrimEnd('\r', '\n');
41
+
42
+ // TODO: Create a separate user for connecting within the application
43
+ // rather than using our superuser
44
+ string alloyDBUser = "postgres";
45
+ string databaseName = configuration["ALLOYDB_DATABASE_NAME"];
46
+ // TODO: Consider splitting workloads into read vs. write and take
47
+ // advantage of the AlloyDB read pools
48
+ string primaryIPAddress = configuration["ALLOYDB_PRIMARY_IP"];
49
+ connectionString = "Host=" +
50
+ primaryIPAddress +
51
+ ";Username=" +
52
+ alloyDBUser +
53
+ ";Password=" +
54
+ alloyDBPassword +
55
+ ";Database=" +
56
+ databaseName;
57
+
58
+ tableName = configuration["ALLOYDB_TABLE_NAME"];
59
+ }
60
+
61
+
62
+ public async Task AddItemAsync(string userId, string productId, int quantity)
63
+ {
64
+ Console.WriteLine($"AddItemAsync for {userId} called");
65
+ try
66
+ {
67
+ await using var dataSource = NpgsqlDataSource.Create(connectionString);
68
+
69
+ var fetchCmd = $"SELECT quantity FROM {tableName} WHERE userID='{userId}' AND productID='{productId}'";
70
+ var currentQuantity = 0;
71
+ var cmdRead = dataSource.CreateCommand(fetchCmd);
72
+ await using (var reader = await cmdRead.ExecuteReaderAsync())
73
+ {
74
+ while (await reader.ReadAsync())
75
+ currentQuantity += reader.GetInt32(0);
76
+ }
77
+
78
+ var totalQuantity = quantity + currentQuantity;
79
+
80
+ // Use INSERT ... ON CONFLICT to prevent duplicate key error
81
+ var insertCmd = $@"
82
+ INSERT INTO {tableName} (userId, productId, quantity)
83
+ VALUES ('{userId}', '{productId}', {totalQuantity})
84
+ ON CONFLICT (userId, productId)
85
+ DO UPDATE SET quantity = {totalQuantity};
86
+ ";
87
+
88
+ await using (var cmdInsert = dataSource.CreateCommand(insertCmd))
89
+ {
90
+ await Task.Run(() =>
91
+ {
92
+ return cmdInsert.ExecuteNonQueryAsync();
93
+ });
94
+ }
95
+ }
96
+ catch (Exception ex)
97
+ {
98
+ throw new RpcException(
99
+ new Status(StatusCode.FailedPrecondition, $"Unable to access cart storage due to an internal error. {ex}"));
100
+ }
101
+ }
102
+
103
+
104
+ public async Task<Hipstershop.Cart> GetCartAsync(string userId)
105
+ {
106
+ Console.WriteLine($"GetCartAsync called for userId={userId}");
107
+ Hipstershop.Cart cart = new();
108
+ cart.UserId = userId;
109
+ try
110
+ {
111
+ await using var dataSource = NpgsqlDataSource.Create(connectionString);
112
+
113
+ var cartFetchCmd = $"SELECT productId, quantity FROM {tableName} WHERE userId = '{userId}'";
114
+ var cmd = dataSource.CreateCommand(cartFetchCmd);
115
+ await using (var reader = await cmd.ExecuteReaderAsync())
116
+ {
117
+ while (await reader.ReadAsync())
118
+ {
119
+ Hipstershop.CartItem item = new()
120
+ {
121
+ ProductId = reader.GetString(0),
122
+ Quantity = reader.GetInt32(1)
123
+ };
124
+ cart.Items.Add(item);
125
+ }
126
+ }
127
+ await Task.Run(() =>
128
+ {
129
+ return cart;
130
+ });
131
+ }
132
+ catch (Exception ex)
133
+ {
134
+ throw new RpcException(
135
+ new Status(StatusCode.FailedPrecondition, $"Unable to access cart storage due to an internal error. {ex}"));
136
+ }
137
+ return cart;
138
+ }
139
+
140
+
141
+ public async Task EmptyCartAsync(string userId)
142
+ {
143
+ Console.WriteLine($"EmptyCartAsync called for userId={userId}");
144
+
145
+ try
146
+ {
147
+ await using var dataSource = NpgsqlDataSource.Create(connectionString);
148
+ var deleteCmd = $"DELETE FROM {tableName} WHERE userID = '{userId}'";
149
+ await using (var cmd = dataSource.CreateCommand(deleteCmd))
150
+ {
151
+ await Task.Run(() =>
152
+ {
153
+ return cmd.ExecuteNonQueryAsync();
154
+ });
155
+ }
156
+ }
157
+ catch (Exception ex)
158
+ {
159
+ throw new RpcException(
160
+ new Status(StatusCode.FailedPrecondition, $"Unable to access cart storage due to an internal error. {ex}"));
161
+ }
162
+ }
163
+
164
+ public bool Ping()
165
+ {
166
+ try
167
+ {
168
+ return true;
169
+ }
170
+ catch (Exception)
171
+ {
172
+ return false;
173
+ }
174
+ }
175
+ }
176
+ }
177
+