Skip to content

Commit

Permalink
Fixes for Owner/SetName.
Browse files Browse the repository at this point in the history
  • Loading branch information
ScottArbeit committed Jul 23, 2024
1 parent 5962f7d commit 578ac82
Show file tree
Hide file tree
Showing 16 changed files with 234 additions and 195 deletions.
7 changes: 5 additions & 2 deletions src/Grace.Actors/Interfaces.Actor.fs
Original file line number Diff line number Diff line change
Expand Up @@ -203,10 +203,13 @@ module Interfaces =
[<Interface>]
type IOwnerNameActor =
inherit IActor
/// Sets the OwnerId for a given OwnerName.
abstract member SetOwnerId: ownerName: OwnerName -> correlationId: CorrelationId -> Task
/// Clears the OwnerId for the given OwnerName.
abstract member ClearOwnerId: correlationId: CorrelationId -> Task
/// Returns the OwnerId for the given OwnerName.
abstract member GetOwnerId: correlationId: CorrelationId -> Task<OwnerId option>
/// Sets the OwnerId for a given OwnerName.
abstract member SetOwnerId: ownerId: OwnerId -> correlationId: CorrelationId -> Task


/// Defines the operations for the Reference actor.
[<Interface>]
Expand Down
14 changes: 13 additions & 1 deletion src/Grace.Actors/Owner.Actor.fs
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,19 @@ module Owner =
task {
match command with
| OwnerCommand.Create(ownerId, ownerName) -> return Ok(OwnerEventType.Created(ownerId, ownerName))
| OwnerCommand.SetName ownerName -> return Ok(OwnerEventType.NameSet ownerName)
| OwnerCommand.SetName newName ->
// Clear the OwnerNameActor for the old name.
let ownerNameActor = actorProxyFactory.CreateActorProxy<IOwnerNameActor>(ActorId(ownerDto.OwnerName), ActorName.OwnerName)
do! ownerNameActor.ClearOwnerId metadata.CorrelationId
memoryCache.Remove($"OwN:{ownerDto.OwnerName}")

// Set the OwnerNameActor for the new name.
let ownerNameActor = actorProxyFactory.CreateActorProxy<IOwnerNameActor>(ActorId(newName), ActorName.OwnerName)
do! ownerNameActor.SetOwnerId ownerDto.OwnerId metadata.CorrelationId
use newCacheEntry =
memoryCache.CreateEntry($"OwN:{newName}", Value = ownerDto.OwnerId, AbsoluteExpirationRelativeToNow = MemoryCache.DefaultExpirationTime)

return Ok(OwnerEventType.NameSet newName)
| OwnerCommand.SetType ownerType -> return Ok(OwnerEventType.TypeSet ownerType)
| OwnerCommand.SetSearchVisibility searchVisibility -> return Ok(OwnerEventType.SearchVisibilitySet searchVisibility)
| OwnerCommand.SetDescription description -> return Ok(OwnerEventType.DescriptionSet description)
Expand Down
13 changes: 8 additions & 5 deletions src/Grace.Actors/OwnerName.Actor.fs
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,18 @@ module OwnerName =
Task.CompletedTask

interface IOwnerNameActor with
member this.ClearOwnerId correlationId =
this.correlationId <- correlationId
cachedOwnerId <- None

Task.CompletedTask

member this.GetOwnerId(correlationId) =
this.correlationId <- correlationId
cachedOwnerId |> returnTask

member this.SetOwnerId (ownerId: string) correlationId =
member this.SetOwnerId (ownerId: OwnerId) correlationId =
this.correlationId <- correlationId
let mutable guid = Guid.Empty

if Guid.TryParse(ownerId, &guid) && guid <> Guid.Empty then
cachedOwnerId <- Some guid
cachedOwnerId <- Some ownerId

Task.CompletedTask
22 changes: 11 additions & 11 deletions src/Grace.Actors/Services.Actor.fs
Original file line number Diff line number Diff line change
Expand Up @@ -262,13 +262,13 @@ module Services =
| AzureCosmosDb ->
let queryDefinition =
QueryDefinition(
"""SELECT events.Event.created.ownerId
"""SELECT c["value"].OwnerId
FROM c
JOIN events IN c["value"]
WHERE ENDSWITH(c.id, @stateStorageName) AND STRINGEQUALS(events.Event.created.ownerName, @ownerName, true)"""
WHERE ENDSWITH(c.id, @stateStorageName)
AND STRINGEQUALS(c["value"].OwnerName, @ownerName, true)"""
)
.WithParameter("@ownerName", ownerName)
.WithParameter("@stateStorageName", StateName.Owner)
.WithParameter("@stateStorageName", StateName.OwnerDto)

let iterator = DefaultRetryPolicy.Execute(fun () -> cosmosContainer.GetItemQueryIterator<OwnerIdRecord>(queryDefinition))
let mutable ownerGuid = OwnerId.Empty
Expand All @@ -279,12 +279,12 @@ module Services =

if String.IsNullOrEmpty(ownerId) && cacheResultIfNotFound then
// We didn't find the OwnerId, so add this OwnerName to the MemoryCache and indicate that we have already checked.
use newCacheEntry =
memoryCache.CreateEntry(
$"OwN:{ownerName}",
Value = MemoryCache.EntityDoesNotExist,
AbsoluteExpirationRelativeToNow = MemoryCache.DefaultExpirationTime
)
//use newCacheEntry =
// memoryCache.CreateEntry(
// $"OwN:{ownerName}",
// Value = MemoryCache.EntityDoesNotExist,
// AbsoluteExpirationRelativeToNow = MemoryCache.DefaultExpirationTime
// )

return false
elif String.IsNullOrEmpty(ownerId) then
Expand All @@ -300,7 +300,7 @@ module Services =
use newCacheEntry2 = memoryCache.CreateEntry(ownerGuid, Value = MemoryCache.ExistsValue, AbsoluteExpirationRelativeToNow = MemoryCache.DefaultExpirationTime)

// Set the OwnerId in the OwnerName actor.
do! ownerNameActorProxy.SetOwnerId ownerId correlationId
do! ownerNameActorProxy.SetOwnerId ownerGuid correlationId
return true
else
return false
Expand Down
13 changes: 7 additions & 6 deletions src/Grace.CLI/Command/Common.CLI.fs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace Grace.CLI
namespace Grace.CLI

open Grace.CLI.Services
open Grace.Shared
open Grace.Shared.Client.Configuration
open Grace.Shared.Resources.Text
Expand Down Expand Up @@ -144,19 +145,19 @@ module Common =
| Error error ->
let json =
if error.Error.Contains("Stack trace") then
Regex.Unescape(error.Error)
Uri.UnescapeDataString(error.Error)
else
Regex.Unescape(serialize error)
Uri.UnescapeDataString(serialize error)

let errorText =
if error.Error.Contains("Stack trace") then
try
let exceptionResponse = deserialize<ExceptionResponse> error.Error
Regex.Unescape($"{exceptionResponse}")
Uri.UnescapeDataString($"{exceptionResponse}")
with ex ->
Regex.Unescape(error.Error)
Uri.UnescapeDataString(error.Error)
else
Regex.Unescape(error.Error)
Uri.UnescapeDataString(error.Error)

match outputFormat with
| Json -> AnsiConsole.WriteLine($"{Markup.Escape(json)}")
Expand Down
19 changes: 17 additions & 2 deletions src/Grace.CLI/Command/Owner.CLI.fs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Grace.CLI.Command
namespace Grace.CLI.Command

open FSharpPlus
open Grace.CLI.Common
Expand Down Expand Up @@ -283,11 +283,26 @@ module Owner =
let t0 = progressContext.AddTask($"[{Color.DodgerBlue1}]Sending command to the server.[/]")

let! result = Owner.SetName(parameters)
match result with
| Ok returnValue ->
// Update the Grace configuration file with the new Owner name.
let newConfig = Current()
newConfig.OwnerName <- returnValue.Properties[setNameParameters.NewName]
updateConfiguration newConfig
| Error _ -> ()
t0.Increment(100.0)
return result
})
else
return! Owner.SetName(parameters)
let! result = Owner.SetName(parameters)
match result with
| Ok graceReturnValue ->
// Update the Grace configuration file with the new Owner name.
let newConfig = Current()
newConfig.OwnerName <-graceReturnValue.Properties[setNameParameters.NewName]
updateConfiguration newConfig
| Error _ -> ()
return result
| Error error -> return Error error
with ex ->
return Error(GraceError.Create $"{Utilities.createExceptionResponse ex}" (parseResult |> getCorrelationId))
Expand Down
4 changes: 2 additions & 2 deletions src/Grace.SDK/Common.SDK.fs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ module Common =
let! errorMessage = response.Content.ReadAsStringAsync()

return
Error(GraceError.Create $"{errorMessage}" parameters.CorrelationId)
Error (GraceError.Create $"{errorMessage}" parameters.CorrelationId)
|> enhance ("ServerResponseTime", $"{(endTime - startTime).TotalMilliseconds:F3} ms")
|> enhance ("StatusCode", $"{response.StatusCode}")
else
Expand All @@ -169,7 +169,7 @@ module Common =
|> enhance ("StatusCode", $"{response.StatusCode}")
with ex ->
let exceptionResponse = Utilities.createExceptionResponse ex
return Error(GraceError.Create ($"{exceptionResponse}") parameters.CorrelationId)
return Error (GraceError.Create ($"{exceptionResponse}") parameters.CorrelationId)
}

/// Ensures that the CorrelationId is set in the parameters for calling Grace Server. If it hasn't already been set, one will be created.
Expand Down
45 changes: 24 additions & 21 deletions src/Grace.Server/Branch.Server.fs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ module Branch =

let actorProxyFactory = ApplicationContext.actorProxyFactory

let getActorProxy (context: HttpContext) (branchId: string) =
let actorId = ActorId($"{branchId}")
let getBranchActorProxy (branchId: string) =
let actorId = ActorId(branchId)
actorProxyFactory.CreateActorProxy<IBranchActor>(actorId, ActorName.Branch)

let processCommand<'T when 'T :> BranchParameters> (context: HttpContext) (validations: Validations<'T>) (command: 'T -> ValueTask<BranchCommand>) =
Expand All @@ -53,7 +53,7 @@ module Branch =

let handleCommand branchId cmd =
task {
let actorProxy = getActorProxy context branchId
let actorProxy = getBranchActorProxy branchId

match! actorProxy.Handle cmd (createMetadata context) with
| Ok graceReturnValue ->
Expand All @@ -73,7 +73,7 @@ module Branch =

return!
context
|> result400BadRequest { graceError with Properties = getPropertiesAsDictionary parameters }
|> result400BadRequest { graceError with Properties = getParametersAsDictionary parameters }
}

let validationResults = validations parameters
Expand Down Expand Up @@ -118,7 +118,7 @@ module Branch =
let errorMessage = BranchError.getErrorMessage error
log.LogDebug("{currentInstant}: error: {error}", getCurrentInstantExtended (), errorMessage)

let graceError = GraceError.CreateWithMetadata errorMessage (getCorrelationId context) (getPropertiesAsDictionary parameters)
let graceError = GraceError.CreateWithMetadata errorMessage (getCorrelationId context) (getParametersAsDictionary parameters)

graceError.Properties.Add("Path", context.Request.Path)
graceError.Properties.Add("Error", errorMessage)
Expand All @@ -141,33 +141,36 @@ module Branch =
use activity = activitySource.StartActivity("processQuery", ActivityKind.Server)

try
let graceIds = getGraceIds context
let validationResults = validations parameters

let! validationsPassed = validationResults |> allPass

if validationsPassed then
match! resolveBranchId parameters.RepositoryId parameters.BranchId parameters.BranchName parameters.CorrelationId with
| Some branchId ->
let actorProxy = getActorProxy context branchId
let! queryResult = query context maxCount actorProxy
// Get the actor proxy for the branch.
let actorProxy = getBranchActorProxy graceIds.BranchId

let graceReturnValue = GraceReturnValue.Create queryResult (getCorrelationId context)
// Execute the query.
let! queryResult = query context maxCount actorProxy

let graceIds = getGraceIds context
graceReturnValue.Properties[nameof (OwnerId)] <- graceIds.OwnerId
graceReturnValue.Properties[nameof (OrganizationId)] <- graceIds.OrganizationId
graceReturnValue.Properties[nameof (RepositoryId)] <- graceIds.RepositoryId
graceReturnValue.Properties[nameof (BranchId)] <- graceIds.BranchId
// Wrap the query result in a GraceReturnValue.
let graceReturnValue =
(GraceReturnValue.Create queryResult (getCorrelationId context))
.enhance(nameof (OwnerId), graceIds.OwnerId)
.enhance(nameof (OrganizationId), graceIds.OrganizationId)
.enhance(nameof (RepositoryId), graceIds.RepositoryId)
.enhance(nameof (BranchId), graceIds.BranchId)

return! context |> result200Ok graceReturnValue
| None ->
return!
context
|> result400BadRequest (GraceError.Create (BranchError.getErrorMessage BranchDoesNotExist) (getCorrelationId context))
return! context |> result200Ok graceReturnValue
else
let! error = validationResults |> getFirstError

let graceError = GraceError.Create (BranchError.getErrorMessage error) (getCorrelationId context)
let graceError =
(GraceError.Create (BranchError.getErrorMessage error) (getCorrelationId context))
.enhance(nameof (OwnerId), graceIds.OwnerId)
.enhance(nameof (OrganizationId), graceIds.OrganizationId)
.enhance(nameof (RepositoryId), graceIds.RepositoryId)
.enhance(nameof (BranchId), graceIds.BranchId)

graceError.Properties.Add("Path", context.Request.Path)
return! context |> result400BadRequest graceError
Expand Down
12 changes: 6 additions & 6 deletions src/Grace.Server/Organization.Server.fs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ module Organization =

let actorProxyFactory = ApplicationContext.actorProxyFactory

let getActorProxy (context: HttpContext) (organizationId: string) =
let getOrganizationActorProxy (organizationId: string) =
let actorId = ActorId(organizationId)
actorProxyFactory.CreateActorProxy<IOrganizationActor>(actorId, ActorName.Organization)

Expand All @@ -55,7 +55,7 @@ module Organization =

let handleCommand organizationId cmd =
task {
let actorProxy = getActorProxy context organizationId
let actorProxy = getOrganizationActorProxy organizationId

match! actorProxy.Handle cmd (createMetadata context) with
| Ok graceReturnValue ->
Expand All @@ -73,7 +73,7 @@ module Organization =

return!
context
|> result400BadRequest { graceError with Properties = getPropertiesAsDictionary parameters }
|> result400BadRequest { graceError with Properties = getParametersAsDictionary parameters }
}

let validationResults = validations parameters
Expand Down Expand Up @@ -121,14 +121,14 @@ module Organization =
GraceError.CreateWithMetadata
(OrganizationError.getErrorMessage OrganizationDoesNotExist)
(getCorrelationId context)
(getPropertiesAsDictionary parameters)
(getParametersAsDictionary parameters)
)
else
let! error = validationResults |> getFirstError
let errorMessage = OrganizationError.getErrorMessage error
log.LogDebug("{currentInstant}: error: {error}", getCurrentInstantExtended (), errorMessage)

let graceError = GraceError.CreateWithMetadata errorMessage (getCorrelationId context) (getPropertiesAsDictionary parameters)
let graceError = GraceError.CreateWithMetadata errorMessage (getCorrelationId context) (getParametersAsDictionary parameters)

graceError.Properties.Add("Path", context.Request.Path)
graceError.Properties.Add("Error", errorMessage)
Expand Down Expand Up @@ -164,7 +164,7 @@ module Organization =

if validationsPassed then
// Get the actor proxy for this organization.
let actorProxy = getActorProxy context graceIds.OrganizationId
let actorProxy = getOrganizationActorProxy graceIds.OrganizationId

// Execute the query.
let! queryResult = query context maxCount actorProxy
Expand Down
Loading

0 comments on commit 578ac82

Please sign in to comment.