This repository has been archived by the owner on Nov 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathPartyServiceImpl.cs
490 lines (421 loc) · 20.5 KB
/
PartyServiceImpl.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core;
using Improbable.OnlineServices.Common;
using Improbable.OnlineServices.Common.Analytics;
using Improbable.OnlineServices.DataModel;
using Improbable.OnlineServices.DataModel.Party;
using Improbable.OnlineServices.Proto.Party;
using MemoryStore;
using Serilog;
using Invite = Improbable.OnlineServices.DataModel.Party.Invite;
using PartyProto = Improbable.OnlineServices.Proto.Party.Party;
using PartyDataModel = Improbable.OnlineServices.DataModel.Party.Party;
using PartyPhaseProto = Improbable.OnlineServices.Proto.Party.Party.Types.Phase;
using PartyPhaseDataModel = Improbable.OnlineServices.DataModel.Party.Party.Phase;
namespace Party
{
// TODO(OS-185): Transition to context based status codes instead of RpcExceptions.
public class PartyServiceImpl : PartyService.PartyServiceBase
{
private readonly IMemoryStoreClientManager<IMemoryStoreClient> _memoryStoreClientManager;
private readonly AnalyticsSenderClassWrapper _analytics;
public PartyServiceImpl(IMemoryStoreClientManager<IMemoryStoreClient> memoryStoreClientManager,
IAnalyticsSender analytics = null)
{
_memoryStoreClientManager = memoryStoreClientManager;
_analytics = (analytics ?? new NullAnalyticsSender()).WithEventClass("party");
}
public override Task<CreatePartyResponse> CreateParty(CreatePartyRequest request, ServerCallContext context)
{
var playerId = AuthHeaders.ExtractPlayerId(context);
var pit = AuthHeaders.ExtractPit(context);
// TODO(iuliaharasim/dom): Move logic specific to party creation in a separate class.
PartyDataModel party;
try
{
party = new PartyDataModel(playerId, pit, request.MinMembers, request.MaxMembers, request.Metadata);
}
catch (ArgumentException exception)
{
throw new RpcException(new Status(StatusCode.InvalidArgument, exception.Message));
}
var leader = party.GetLeader();
using (var memClient = _memoryStoreClientManager.GetClient())
using (var transaction = memClient.CreateTransaction())
{
transaction.CreateAll(new List<Entry> { party, leader });
}
var eventAttributes = new Dictionary<string, string>
{
{ "partyId", party.Id }
};
string[] eventTypes = { "player_created_party", "player_joined_party", "party_created" };
foreach (string eventType in eventTypes)
{
if (eventType == "party_created")
{
eventAttributes.Add("partyPhase", party.CurrentPhase.ToString());
}
_analytics.Send(eventType, eventAttributes, playerId);
}
return Task.FromResult(new CreatePartyResponse { PartyId = party.Id });
}
public override async Task<GetPartyByPlayerIdResponse> GetPartyByPlayerId(GetPartyByPlayerIdRequest request,
ServerCallContext context)
{
var playerId = AuthHeaders.ExtractPlayerId(context);
using (var memClient = _memoryStoreClientManager.GetClient())
{
var party = await GetPartyByPlayerId(memClient, playerId) ??
throw new RpcException(new Status(StatusCode.NotFound,
"The player is not a member of any party"));
return new GetPartyByPlayerIdResponse { Party = ConvertToProto(party) };
}
}
public override async Task<DeletePartyResponse> DeleteParty(DeletePartyRequest request,
ServerCallContext context)
{
var playerId = AuthHeaders.ExtractPlayerId(context);
using (var memClient = _memoryStoreClientManager.GetClient())
{
var party = await GetPartyByPlayerId(memClient, playerId) ??
throw new RpcException(new Status(StatusCode.NotFound,
"The player is not a member of any party"));
if (playerId != party.LeaderPlayerId)
{
throw new RpcException(new Status(StatusCode.PermissionDenied,
"Cannot delete party: player needs to be the leader of the party"));
}
// TODO(iuliaharasim/dom): Move logic specific to party deletion in a separate class.
var entitiesToDelete = new List<Entry> { party };
entitiesToDelete.AddRange(party.GetMembers());
try
{
using (var transaction = memClient.CreateTransaction())
{
transaction.DeleteAll(entitiesToDelete);
}
}
catch (EntryNotFoundException exception)
{
if (exception.Id.Contains(party.Id))
{
throw;
}
// If one of the members has left the party, it is safe to retry this RPC.
throw new TransactionAbortedException();
}
_analytics.Send("player_cancelled_party", new Dictionary<string, string> { { "partyId", party.Id } }, playerId);
_analytics.Send("party_cancelled", new Dictionary<string, string> { { "partyId", party.Id } }, playerId);
foreach (var m in party.GetMembers())
{
_analytics.Send(
"player_left_cancelled_party", new Dictionary<string, string>
{
{ "partyId", party.Id }
}, m.Id);
}
}
return new DeletePartyResponse();
}
public override async Task<JoinPartyResponse> JoinParty(JoinPartyRequest request, ServerCallContext context)
{
var playerId = AuthHeaders.ExtractPlayerId(context);
var pit = AuthHeaders.ExtractPit(context);
if (string.IsNullOrEmpty(request.PartyId))
{
throw new RpcException(new Status(StatusCode.InvalidArgument,
"JoinParty requires a non-empty party id"));
}
using (var memClient = _memoryStoreClientManager.GetClient())
{
var partyToJoin = await memClient.GetAsync<PartyDataModel>(request.PartyId) ??
throw new RpcException(new Status(StatusCode.NotFound, "The party doesn't exist"));
var member = await memClient.GetAsync<Member>(playerId);
if (member != null && member.PartyId != request.PartyId)
{
throw new RpcException(new Status(StatusCode.AlreadyExists,
"The player is a member of another party"));
}
var playerInvites = await memClient.GetAsync<PlayerInvites>(playerId);
if (playerInvites == null)
{
throw new RpcException(new Status(StatusCode.FailedPrecondition,
"The player is not invited to this party"));
}
var invites = (await Task.WhenAll(playerInvites.InboundInviteIds
.Select(invite => memClient.GetAsync<Invite>(invite))))
.Where(invite =>
{
if (invite == null)
{
Log.Logger.Warning("Failed to fetch an invite for {player}", playerId);
}
return invite != null;
}).ToList();
var invited = invites
.Any(invite => invite.CurrentStatus == Invite.Status.Pending && invite.ReceiverId == playerId);
if (!invited)
{
throw new RpcException(new Status(StatusCode.FailedPrecondition,
"The player is not invited to this party"));
}
if (partyToJoin.CurrentPhase != PartyPhaseDataModel.Forming)
{
throw new RpcException(new Status(StatusCode.FailedPrecondition,
"The party is no longer in the Forming phase"));
}
// TODO(iuliaharasim/dom): Move logic specific to joining a party into a separate class.
try
{
var added = partyToJoin.AddPlayerToParty(playerId, pit);
// If false, the player already joined the party so we should terminate early.
if (!added)
{
return new JoinPartyResponse { Party = ConvertToProto(partyToJoin) };
}
}
catch (Exception exception)
{
throw new RpcException(new Status(StatusCode.FailedPrecondition, exception.Message));
}
using (var transaction = memClient.CreateTransaction())
{
transaction.CreateAll(new List<Entry> { partyToJoin.GetMember(playerId) });
transaction.UpdateAll(new List<Entry> { partyToJoin });
}
_analytics.Send("player_joined_party", new Dictionary<string, object>
{
{ "partyId", partyToJoin.Id },
{
"invites", invites.Select(invite => new Dictionary<string, string>
{
{ "inviteId", invite.Id },
{ "playerIdInviter", invite.SenderId }
})
}
}, playerId);
return new JoinPartyResponse { Party = ConvertToProto(partyToJoin) };
}
}
public override async Task<LeavePartyResponse> LeaveParty(LeavePartyRequest request, ServerCallContext context)
{
var playerId = AuthHeaders.ExtractPlayerId(context);
await LeaveParty(playerId);
return new LeavePartyResponse();
}
public override async Task<KickOutPlayerResponse> KickOutPlayer(KickOutPlayerRequest request,
ServerCallContext context)
{
var playerId = AuthHeaders.ExtractPlayerId(context);
if (string.IsNullOrEmpty(request.EvictedPlayerId))
{
throw new RpcException(new Status(StatusCode.InvalidArgument,
"LeaveParty requires a non-empty evicted player id"));
}
if (playerId == request.EvictedPlayerId)
{
await LeaveParty(request.EvictedPlayerId);
return new KickOutPlayerResponse();
}
using (var memClient = _memoryStoreClientManager.GetClient())
{
var initiatorTask = memClient.GetAsync<Member>(playerId);
var evictedTask = memClient.GetAsync<Member>(request.EvictedPlayerId);
Task.WaitAll(initiatorTask, evictedTask);
var initiator = initiatorTask.Result ?? throw new RpcException(new Status(StatusCode.NotFound,
"The initiator player is not a member of any party"));
// If the evicted has already left the party, we should return early.
var evicted = evictedTask.Result;
if (evicted == null)
{
return new KickOutPlayerResponse();
}
var party = await memClient.GetAsync<PartyDataModel>(initiator.PartyId) ??
throw new RpcException(new Status(StatusCode.NotFound,
"The party no longer exists"));
if (party.LeaderPlayerId != initiator.Id)
{
throw new RpcException(new Status(StatusCode.PermissionDenied,
"The initiator is not the leader of the party"));
}
if (initiator.PartyId != evicted.PartyId)
{
throw new RpcException(new Status(StatusCode.PermissionDenied,
"The players are not members of the same party"));
}
// TODO(iuliaharasim/dom): Move logic specific to removing a player from a party into a separate class.
// If false, the player has already been removed from the party so we should terminate early.
if (!party.RemovePlayerFromParty(evicted.Id))
{
return new KickOutPlayerResponse();
}
using (var transaction = memClient.CreateTransaction())
{
transaction.DeleteAll(new List<Entry> { evicted });
transaction.UpdateAll(new List<Entry> { party });
}
_analytics.Send("player_kicked_from_party", new Dictionary<string, string>
{
{ "partyId", party.Id },
{ "playerIdKicker", playerId }
}, evicted.Id);
}
return new KickOutPlayerResponse();
}
private async Task LeaveParty(string playerId)
{
using (var memClient = _memoryStoreClientManager.GetClient())
{
var memberToDelete = await memClient.GetAsync<Member>(playerId);
// We should terminate early if the player has already left the party.
if (memberToDelete == null)
{
return;
}
var party = await memClient.GetAsync<PartyDataModel>(memberToDelete.PartyId) ??
throw new RpcException(new Status(StatusCode.NotFound,
"The party no longer exists"));
try
{
// We should terminate early if the player has already left the party.
if (!party.RemovePlayerFromParty(playerId))
{
return;
}
}
catch (Exception exception)
{
throw new RpcException(new Status(StatusCode.FailedPrecondition, exception.Message));
}
// TODO(iuliaharasim/dom): Move logic specific to leaving a party into a separate class.
using (var transaction = memClient.CreateTransaction())
{
transaction.DeleteAll(new List<Entry> { memberToDelete });
transaction.UpdateAll(new List<Entry> { party });
}
_analytics.Send("player_left_party", new Dictionary<string, string>
{
{ "partyId", party.Id }
}, playerId);
}
}
// Updates the Party's information, excluding its member list.
// TODO: Move to FieldMasks.
public override async Task<UpdatePartyResponse> UpdateParty(UpdatePartyRequest request,
ServerCallContext context)
{
var playerId = AuthHeaders.ExtractPlayerId(context);
ValidateUpdatePartyRequest(request);
using (var memClient = _memoryStoreClientManager.GetClient())
{
var updatedParty = request.UpdatedParty;
var party = await memClient.GetAsync<PartyDataModel>(updatedParty.Id) ??
throw new RpcException(new Status(StatusCode.NotFound,
"There is no such party with the given id"));
if (party.LeaderPlayerId != playerId)
{
throw new RpcException(new Status(StatusCode.PermissionDenied,
"The update operation can only be done by the leader of the party"));
}
if (!party.UpdatePartyLeader(updatedParty.LeaderPlayerId))
{
throw new RpcException(new Status(StatusCode.FailedPrecondition,
"The proposed new leader is not a member of the party"));
}
if (!party.UpdateMinMaxMembers(updatedParty.MinMembers, updatedParty.MaxMembers))
{
throw new RpcException(new Status(StatusCode.FailedPrecondition,
"Encountered error while updating the minimum and maximum amount of members"));
}
// TODO(iuliaharasim/dom): Move logic specific to updating a party into a separate class.
party.CurrentPhase = ConvertToDataModel(updatedParty.CurrentPhase);
party.UpdateMetadata(updatedParty.Metadata);
using (var transaction = memClient.CreateTransaction())
{
transaction.UpdateAll(new List<Entry> { party });
}
var eventAttributes = new Dictionary<string, object>
{
{ "partyId", updatedParty.Id },
{
"newPartyState", new Dictionary<string, object>
{
{ "partyLeaderId", updatedParty.LeaderPlayerId },
{ "maxMembers", updatedParty.MaxMembers },
{ "minMembers", updatedParty.MinMembers }
}
}
};
_analytics.Send("player_updated_party", eventAttributes, playerId);
var eventAttributesParty = new Dictionary<string, object>(eventAttributes) { { "partyPhase", updatedParty.CurrentPhase.ToString() } };
_analytics.Send("party_updated", eventAttributesParty, playerId);
return new UpdatePartyResponse { Party = ConvertToProto(party) };
}
}
private static void ValidateUpdatePartyRequest(UpdatePartyRequest request)
{
var updatedParty = request.UpdatedParty ??
throw new RpcException(new Status(StatusCode.InvalidArgument,
"UpdatePartyInfo requires a non-empty updated party"));
if (string.IsNullOrEmpty(updatedParty.Id))
{
throw new RpcException(new Status(StatusCode.InvalidArgument,
"UpdatePartyInfo requires an updated party with a non-empty id"));
}
}
private static async Task<PartyDataModel> GetPartyByPlayerId(IMemoryStoreClient memClient, string playerId)
{
var member = await memClient.GetAsync<Member>(playerId);
if (member == null)
{
return null;
}
return await memClient.GetAsync<PartyDataModel>(member.PartyId);
}
private static PartyProto ConvertToProto(PartyDataModel party)
{
return new PartyProto
{
Id = party.Id,
LeaderPlayerId = party.LeaderPlayerId,
MinMembers = party.MinMembers,
MaxMembers = party.MaxMembers,
Metadata = { party.Metadata },
MemberIds = { party.MemberIds },
CurrentPhase = ConvertToProto(party.CurrentPhase)
};
}
private static PartyPhaseProto ConvertToProto(PartyPhaseDataModel phase)
{
switch (phase)
{
case PartyPhaseDataModel.Forming:
return PartyPhaseProto.Forming;
case PartyPhaseDataModel.Matchmaking:
return PartyPhaseProto.Matchmaking;
case PartyPhaseDataModel.InGame:
return PartyPhaseProto.InGame;
default:
return PartyPhaseProto.Unknown;
}
}
private static PartyPhaseDataModel ConvertToDataModel(PartyPhaseProto phase)
{
switch (phase)
{
case PartyPhaseProto.Forming:
return PartyPhaseDataModel.Forming;
case PartyPhaseProto.Matchmaking:
return PartyPhaseDataModel.Matchmaking;
case PartyPhaseProto.InGame:
return PartyPhaseDataModel.InGame;
default:
return PartyPhaseDataModel.Unknown;
}
}
}
}