diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 0f3bba5..0000000 --- a/.editorconfig +++ /dev/null @@ -1,153 +0,0 @@ -[*.cs] -csharp_indent_labels = one_less_than_current -csharp_using_directive_placement = outside_namespace:silent -csharp_prefer_simple_using_statement = true:suggestion -csharp_prefer_braces = true:silent -csharp_style_namespace_declarations = file_scoped:error -csharp_style_prefer_method_group_conversion = true:silent -csharp_style_prefer_top_level_statements = true:silent -csharp_style_expression_bodied_methods = false:silent -csharp_style_expression_bodied_constructors = false:silent -csharp_style_expression_bodied_operators = false:silent -csharp_style_expression_bodied_properties = true:silent -csharp_style_expression_bodied_indexers = true:silent -csharp_style_expression_bodied_accessors = true:silent -csharp_style_expression_bodied_lambdas = true:silent -csharp_style_expression_bodied_local_functions = false:silent -csharp_style_throw_expression = true:suggestion -csharp_style_prefer_null_check_over_type_check = true:suggestion -csharp_prefer_simple_default_expression = true:suggestion -csharp_style_prefer_local_over_anonymous_function = true:suggestion -csharp_style_prefer_index_operator = true:suggestion -csharp_style_prefer_range_operator = true:suggestion -csharp_style_implicit_object_creation_when_type_is_apparent = true:error -csharp_style_prefer_tuple_swap = true:suggestion -csharp_prefer_static_local_function = true:suggestion -csharp_style_prefer_readonly_struct = true:suggestion -csharp_style_prefer_utf8_string_literals = true:suggestion -csharp_style_inlined_variable_declaration = true:suggestion -csharp_style_deconstructed_variable_declaration = true:suggestion -csharp_style_unused_value_expression_statement_preference = discard_variable:silent -csharp_style_unused_value_assignment_preference = discard_variable:suggestion -csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent -csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent -csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent -csharp_style_conditional_delegate_call = true:suggestion -csharp_style_prefer_pattern_matching = true:silent -csharp_style_prefer_switch_expression = true:suggestion -csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion -csharp_style_pattern_matching_over_as_with_null_check = true:suggestion -csharp_style_prefer_not_pattern = true:suggestion -csharp_style_prefer_extended_property_pattern = true:suggestion -csharp_style_var_for_built_in_types = true:error -csharp_style_var_when_type_is_apparent = true:error -csharp_style_var_elsewhere = false:silent -csharp_space_around_binary_operators = before_and_after -[*.{cs,vb}] -#### Naming styles #### - -# Naming rules - -dotnet_naming_rule.interface_should_be_begins_with_i.severity = error -dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface -dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i - -dotnet_naming_rule.types_should_be_pascal_case.severity = error -dotnet_naming_rule.types_should_be_pascal_case.symbols = types -dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case - -dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = error -dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case - -# Symbol specifications - -dotnet_naming_symbols.interface.applicable_kinds = interface -dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = - -dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = - -dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method -dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = - -# Naming styles - -dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = -dotnet_naming_style.begins_with_i.capitalization = pascal_case - -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case - -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case -dotnet_style_operator_placement_when_wrapping = beginning_of_line -tab_width = 4 -indent_size = 4 -end_of_line = crlf -dotnet_style_coalesce_expression = true:suggestion -dotnet_style_null_propagation = true:suggestion -dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion -dotnet_style_prefer_auto_properties = true:silent -dotnet_style_object_initializer = true:suggestion -dotnet_style_collection_initializer = true:suggestion -dotnet_style_prefer_simplified_boolean_expressions = true:suggestion -dotnet_style_prefer_conditional_expression_over_assignment = true:silent -dotnet_style_prefer_conditional_expression_over_return = true:silent -dotnet_style_explicit_tuple_names = true:suggestion -dotnet_style_prefer_inferred_tuple_names = true:suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion -dotnet_style_prefer_compound_assignment = true:suggestion -dotnet_style_prefer_simplified_interpolation = true:error -dotnet_style_namespace_match_folder = true:error -dotnet_style_require_accessibility_modifiers = always:error -dotnet_style_readonly_field = true:suggestion -dotnet_style_predefined_type_for_locals_parameters_members = true:silent -dotnet_style_predefined_type_for_member_access = true:silent - -dotnet_naming_symbols.private_fields.applicable_kinds = field -dotnet_naming_symbols.private_fields.applicable_accessibilities = private - -dotnet_naming_style.underscored.capitalization = camel_case -dotnet_naming_style.underscored.required_prefix = _ - -dotnet_naming_rule.private_fields_underscored.symbols = private_fields -dotnet_naming_rule.private_fields_underscored.style = underscored -dotnet_naming_rule.private_fields_underscored.severity = error - -dotnet_naming_rule.constants_must_be_uppercase.symbols = public_constants -dotnet_naming_symbols.public_constants.applicable_kinds = field -dotnet_naming_symbols.public_constants.applicable_accessibilities = * -dotnet_naming_symbols.public_constants.required_modifiers = const - -dotnet_naming_rule.constants_must_be_uppercase.style = pascal_case -dotnet_naming_style.uppercase_with_underscore_separator.capitalization = pascal_case - -dotnet_naming_rule.constants_must_be_uppercase.severity = error -dotnet_style_allow_multiple_blank_lines_experimental = true:silent -dotnet_style_allow_statement_immediately_after_block_experimental = true:silent -dotnet_code_quality_unused_parameters = all:suggestion -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent -dotnet_style_qualification_for_field = false:silent -dotnet_style_qualification_for_property = false:silent -dotnet_style_qualification_for_method = false:silent -dotnet_style_qualification_for_event = false:silent - -# For variables -dotnet_naming_symbols.local_symbol.applicable_kinds = local -dotnet_naming_style.local_style.capitalization = camel_case -dotnet_naming_rule.variables_are_camel_case.severity = error -dotnet_naming_rule.variables_are_camel_case.symbols = local_symbol -dotnet_naming_rule.variables_are_camel_case.style = local_style \ No newline at end of file diff --git a/.gitignore b/.gitignore index ce89292..9b135ed 100644 --- a/.gitignore +++ b/.gitignore @@ -415,4 +415,4 @@ FodyWeavers.xsd *.msi *.msix *.msm -*.msp +*.msp \ No newline at end of file diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj new file mode 100644 index 0000000..929948f --- /dev/null +++ b/Api.Gateway/Api.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/Api.Gateway/Api.Gateway.csproj.user b/Api.Gateway/Api.Gateway.csproj.user new file mode 100644 index 0000000..ccfffb1 --- /dev/null +++ b/Api.Gateway/Api.Gateway.csproj.user @@ -0,0 +1,6 @@ + + + + https + + \ No newline at end of file diff --git a/Api.Gateway/LoadBalancers/QueryBasedLoadBalancer.cs b/Api.Gateway/LoadBalancers/QueryBasedLoadBalancer.cs new file mode 100644 index 0000000..224ced9 --- /dev/null +++ b/Api.Gateway/LoadBalancers/QueryBasedLoadBalancer.cs @@ -0,0 +1,35 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Api.Gateway.LoadBalancers; + +/// +/// Балансировщик нагрузки на основе query-параметра id +/// Определяет реплику по остатку от деления идентификатора на число реплик +/// +/// Делегат для получения списка доступных реплик +public class QueryBased(Func>> services) : ILoadBalancer +{ + private readonly Func>> _services = services; + + public string Type => nameof(QueryBased); + + public async Task> LeaseAsync(HttpContext httpContext) + { + var availableServices = await _services.Invoke(); + var replicaCount = availableServices.Count; + + var replicaIndex = 0; + + if (httpContext.Request.Query.TryGetValue("id", out var rawId) + && int.TryParse(rawId, out var employeeId)) + { + replicaIndex = Math.Abs(employeeId) % replicaCount; + } + + return new OkResponse(availableServices[replicaIndex].HostAndPort); + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} diff --git a/Api.Gateway/Program.cs b/Api.Gateway/Program.cs new file mode 100644 index 0000000..e34dc82 --- /dev/null +++ b/Api.Gateway/Program.cs @@ -0,0 +1,30 @@ +using Api.Gateway.LoadBalancers; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.Services.AddServiceDiscovery(); +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); +builder.Services.AddOcelot() + .AddCustomLoadBalancer((_, _, discoveryProvider) => new(discoveryProvider.GetAsync)); + +var clientOrigin = builder.Configuration["ClientOrigin"] + ?? throw new InvalidOperationException("ClientOrigin is not configured"); + +builder.Services.AddCors(options => options.AddDefaultPolicy(policy => +{ + policy.WithOrigins(clientOrigin); + policy.WithMethods("GET"); + policy.AllowAnyHeader(); +})); + +var app = builder.Build(); + +app.UseCors(); +app.MapDefaultEndpoints(); + +await app.UseOcelot(); + +app.Run(); diff --git a/Api.Gateway/Properties/launchSettings.json b/Api.Gateway/Properties/launchSettings.json new file mode 100644 index 0000000..8ac40a2 --- /dev/null +++ b/Api.Gateway/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:11915", + "sslPort": 44365 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5162", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7027;http://localhost:5162", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Api.Gateway/appsettings.Development.json b/Api.Gateway/appsettings.Development.json new file mode 100644 index 0000000..ff66ba6 --- /dev/null +++ b/Api.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Api.Gateway/appsettings.json b/Api.Gateway/appsettings.json new file mode 100644 index 0000000..0a8ef0b --- /dev/null +++ b/Api.Gateway/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "ClientOrigin": "https://localhost:7282" +} diff --git a/Api.Gateway/ocelot.json b/Api.Gateway/ocelot.json new file mode 100644 index 0000000..f61c6ab --- /dev/null +++ b/Api.Gateway/ocelot.json @@ -0,0 +1,20 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/api/employees", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { "Host": "localhost", "Port": 5100 }, + { "Host": "localhost", "Port": 5101 }, + { "Host": "localhost", "Port": 5102 }, + { "Host": "localhost", "Port": 5103 }, + { "Host": "localhost", "Port": 5104 } + ], + "UpstreamPathTemplate": "/employees", + "UpstreamHttpMethod": [ "Get" ], + "LoadBalancerOptions": { + "Type": "QueryBased" + } + } + ] +} diff --git a/Client.Wasm/Client.Wasm.csproj.user b/Client.Wasm/Client.Wasm.csproj.user new file mode 100644 index 0000000..ccfffb1 --- /dev/null +++ b/Client.Wasm/Client.Wasm.csproj.user @@ -0,0 +1,6 @@ + + + + https + + \ No newline at end of file diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..77cdb3a 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №2 "Балансировка нагрузки" + Вариант №49 "Сотрудник компании" + Выполнена Панюшкиным Андрем 6513 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea..60120ec 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -12,7 +12,7 @@ "http": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "http://localhost:5127", "environmentVariables": { @@ -22,7 +22,7 @@ "https": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "https://localhost:7282;http://localhost:5127", "environmentVariables": { @@ -31,7 +31,7 @@ }, "IIS Express": { "commandName": "IISExpress", - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab..9532148 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7027/employees" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241..a7e6ea0 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,25 +1,49 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.14.36811.4 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {90FE6B04-8381-437E-893A-FEBA1DA10AEE} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36811.4 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EmployeeApp.AppHost", "EmployeeApp\EmployeeApp.AppHost\EmployeeApp.AppHost.csproj", "{2EF7E965-1A57-4198-93B5-5E5F63EAA4B2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EmployeeApp.ServiceDefaults", "EmployeeApp\EmployeeApp.ServiceDefaults\EmployeeApp.ServiceDefaults.csproj", "{2FA6E085-0B95-101F-0B19-42856D8FFBF9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EmployeeApp.Api", "EmployeeApp.Api\EmployeeApp.Api.csproj", "{4FE86887-5370-BEE6-70F2-476C725D7719}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU + {2EF7E965-1A57-4198-93B5-5E5F63EAA4B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2EF7E965-1A57-4198-93B5-5E5F63EAA4B2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2EF7E965-1A57-4198-93B5-5E5F63EAA4B2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2EF7E965-1A57-4198-93B5-5E5F63EAA4B2}.Release|Any CPU.Build.0 = Release|Any CPU + {2FA6E085-0B95-101F-0B19-42856D8FFBF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2FA6E085-0B95-101F-0B19-42856D8FFBF9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2FA6E085-0B95-101F-0B19-42856D8FFBF9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2FA6E085-0B95-101F-0B19-42856D8FFBF9}.Release|Any CPU.Build.0 = Release|Any CPU + {4FE86887-5370-BEE6-70F2-476C725D7719}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4FE86887-5370-BEE6-70F2-476C725D7719}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4FE86887-5370-BEE6-70F2-476C725D7719}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4FE86887-5370-BEE6-70F2-476C725D7719}.Release|Any CPU.Build.0 = Release|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {90FE6B04-8381-437E-893A-FEBA1DA10AEE} + EndGlobalSection +EndGlobal diff --git a/EmployeeApp.Api/EmployeeApp.Api.csproj b/EmployeeApp.Api/EmployeeApp.Api.csproj new file mode 100644 index 0000000..bc55671 --- /dev/null +++ b/EmployeeApp.Api/EmployeeApp.Api.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + + diff --git a/EmployeeApp.Api/EmployeeApp.Api.csproj.user b/EmployeeApp.Api/EmployeeApp.Api.csproj.user new file mode 100644 index 0000000..ccfffb1 --- /dev/null +++ b/EmployeeApp.Api/EmployeeApp.Api.csproj.user @@ -0,0 +1,6 @@ + + + + https + + \ No newline at end of file diff --git a/EmployeeApp.Api/Entities/Employee.cs b/EmployeeApp.Api/Entities/Employee.cs new file mode 100644 index 0000000..fccbab0 --- /dev/null +++ b/EmployeeApp.Api/Entities/Employee.cs @@ -0,0 +1,57 @@ +namespace EmployeeApp.Api.Entities; + +/// +/// Сотрудник компании +/// +public class Employee +{ + /// + /// Идентификатор сотрудника в системе + /// + public int Id { get; set; } + + /// + /// ФИО + /// + public required string FullName { get; set; } + + /// + /// Должность + /// + public required string Position { get; set; } + + /// + /// Отдел + /// + public required string Department { get; set; } + + /// + /// Дата приема + /// + public DateOnly HireDate { get; set; } + + /// + /// Оклад + /// + public decimal Salary { get; set; } + + /// + /// Электронная почта + /// + public required string Email { get; set; } + + /// + /// Номер телефона + /// + public required string PhoneNumber { get; set; } + + /// + /// Индикатор увольнения + /// + public bool IsDismissed { get; set; } + + /// + /// Дата увольнения + /// + public DateOnly? DismissalDate { get; set; } +} diff --git a/EmployeeApp.Api/Program.cs b/EmployeeApp.Api/Program.cs new file mode 100644 index 0000000..572bc27 --- /dev/null +++ b/EmployeeApp.Api/Program.cs @@ -0,0 +1,17 @@ +using EmployeeApp.Api.Services; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("cache"); + +builder.Services.AddScoped(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +app.MapGet("/api/employees", async (IEmployeeService service, int id) => + await service.GetEmployeeById(id)); + +app.Run(); diff --git a/EmployeeApp.Api/Properties/launchSettings.json b/EmployeeApp.Api/Properties/launchSettings.json new file mode 100644 index 0000000..ace0780 --- /dev/null +++ b/EmployeeApp.Api/Properties/launchSettings.json @@ -0,0 +1,13 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/EmployeeApp.Api/Services/EmployeeGenerator.cs b/EmployeeApp.Api/Services/EmployeeGenerator.cs new file mode 100644 index 0000000..2976281 --- /dev/null +++ b/EmployeeApp.Api/Services/EmployeeGenerator.cs @@ -0,0 +1,91 @@ +using Bogus; +using Bogus.DataSets; +using EmployeeApp.Api.Entities; + +namespace EmployeeApp.Api.Services; + +/// +/// Генератор данных сотрудников на основе Bogus +/// +public static class EmployeeGenerator +{ + private static readonly string[] _positions = + ["Developer", "Manager", "Analyst", "Designer", "Tester", "DevOps Engineer", "Architect", "Consultant"]; + + private static readonly string[] _suffixes = + ["Junior", "Middle", "Senior", "Lead", "Principal"]; + + private static readonly Dictionary _salaryRanges = new() + { + ["Junior"] = (30_000m, 100_000m), + ["Middle"] = (100_000m, 250_000m), + ["Senior"] = (250_000m, 300_000m), + ["Lead"] = (300_000m, 500_000m), + ["Principal"] = (180_000m, 250_000m) + }; + + /// + /// Генерация отчества на основе имени и пола + /// + private static string GeneratePatronymic(Faker f, Name.Gender gender) + { + var fatherName = f.Name.FirstName(Name.Gender.Male); + return gender == Name.Gender.Male + ? fatherName + "ович" + : fatherName + "овна"; + } + + /// + /// Генерация фамилии с учётом пола + /// + private static string GenerateLastName(Faker f, Name.Gender gender) + { + var lastName = f.Name.LastName(Name.Gender.Male); + return gender == Name.Gender.Female + ? lastName + "а" + : lastName; + } + + private static readonly Faker _faker = new Faker("ru") + .RuleFor(e => e.FullName, f => + { + var gender = f.PickRandom(); + var lastName = GenerateLastName(f, gender); + var firstName = f.Name.FirstName(gender); + var patronymic = GeneratePatronymic(f, gender); + return $"{lastName} {firstName} {patronymic}"; + }) + .RuleFor(e => e.Position, (f, _) => + { + var suffix = f.PickRandom(_suffixes); + var position = f.PickRandom(_positions); + return $"{suffix} {position}"; + }) + .RuleFor(e => e.Department, f => f.Commerce.Department()) + .RuleFor(e => e.HireDate, f => + DateOnly.FromDateTime(f.Date.Past(10))) + .RuleFor(e => e.Salary, (f, e) => + { + var suffix = e.Position.Split(' ')[0]; + var (min, max) = _salaryRanges.GetValueOrDefault(suffix, (30_000m, 60_000m)); + return Math.Round(f.Random.Decimal(min, max), 2); + }) + .RuleFor(e => e.Email, f => f.Internet.Email()) + .RuleFor(e => e.PhoneNumber, f => + f.Phone.PhoneNumber("+7(###)###-##-##")) + .RuleFor(e => e.IsDismissed, f => f.Random.Bool(0.2f)) + .RuleFor(e => e.DismissalDate, (f, e) => + e.IsDismissed + ? DateOnly.FromDateTime(f.Date.Between(e.HireDate.ToDateTime(TimeOnly.MinValue), DateTime.Now)) + : null); + + /// + /// Генерация сотрудника по идентификатору + /// + public static Employee Generate(int id) + { + var employee = _faker.Generate(); + employee.Id = id; + return employee; + } +} diff --git a/EmployeeApp.Api/Services/EmployeeService.cs b/EmployeeApp.Api/Services/EmployeeService.cs new file mode 100644 index 0000000..e9c6e9f --- /dev/null +++ b/EmployeeApp.Api/Services/EmployeeService.cs @@ -0,0 +1,58 @@ +using System.Text.Json; +using EmployeeApp.Api.Entities; +using Microsoft.Extensions.Caching.Distributed; + +namespace EmployeeApp.Api.Services; + +/// +/// Реализация сервиса генерации данных сотрудников с кешированием +/// +public class EmployeeService(IDistributedCache cache, ILogger logger, IConfiguration configuration) : IEmployeeService +{ + private readonly DistributedCacheEntryOptions _cacheOptions = new() + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(configuration.GetValue("CacheLifetimeMinutes", 5)) + }; + + /// + public async Task GetEmployeeById(int id) + { + var cacheKey = $"employee:{id}"; + + logger.LogInformation("Requesting employee with Id {Id}", id); + + try + { + var cached = await cache.GetStringAsync(cacheKey); + if (cached is not null) + { + var cachedEmployee = JsonSerializer.Deserialize(cached); + if (cachedEmployee is not null) + { + logger.LogInformation("Cache hit for employee {Id}", id); + return cachedEmployee; + } + } + } + catch (Exception ex) + { + logger.LogError(ex, "Error reading cache for employee {Id}", id); + } + + logger.LogInformation("Cache miss for employee {Id}", id); + + var employee = EmployeeGenerator.Generate(id); + + try + { + await cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(employee), _cacheOptions); + logger.LogInformation("Generated and cached employee {Id}", id); + } + catch (Exception ex) + { + logger.LogError(ex, "Error writing cache for employee {Id}", id); + } + + return employee; + } +} diff --git a/EmployeeApp.Api/Services/IEmployeeService.cs b/EmployeeApp.Api/Services/IEmployeeService.cs new file mode 100644 index 0000000..5ce35c7 --- /dev/null +++ b/EmployeeApp.Api/Services/IEmployeeService.cs @@ -0,0 +1,14 @@ +using EmployeeApp.Api.Entities; + +namespace EmployeeApp.Api.Services; + +/// +/// Сервис генерации данных сотрудников +/// +public interface IEmployeeService +{ + /// + /// Получить сотрудника по идентификатору + /// + public Task GetEmployeeById(int id); +} diff --git a/EmployeeApp.Api/appsettings.Development.json b/EmployeeApp.Api/appsettings.Development.json new file mode 100644 index 0000000..ff66ba6 --- /dev/null +++ b/EmployeeApp.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/EmployeeApp.Api/appsettings.json b/EmployeeApp.Api/appsettings.json new file mode 100644 index 0000000..5f6bb9b --- /dev/null +++ b/EmployeeApp.Api/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "CacheLifetimeMinutes": 5 +} diff --git a/EmployeeApp/EmployeeApp.AppHost/AppHost.cs b/EmployeeApp/EmployeeApp.AppHost/AppHost.cs new file mode 100644 index 0000000..e80e57c --- /dev/null +++ b/EmployeeApp/EmployeeApp.AppHost/AppHost.cs @@ -0,0 +1,20 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("cache") + .WithRedisInsight(); + +var apiGateway = builder.AddProject("api-gateway"); + +for (var i = 0; i < 5; i++) +{ + var service = builder.AddProject($"employee-app-{i}", launchProfileName: null) + .WithReference(cache) + .WaitFor(cache) + .WithHttpsEndpoint(port: 5100 + i, name: $"employee-https-{i}"); + apiGateway.WaitFor(service); +} + +builder.AddProject("client-wasm") + .WaitFor(apiGateway); + +builder.Build().Run(); diff --git a/EmployeeApp/EmployeeApp.AppHost/EmployeeApp.AppHost.csproj b/EmployeeApp/EmployeeApp.AppHost/EmployeeApp.AppHost.csproj new file mode 100644 index 0000000..36e6e11 --- /dev/null +++ b/EmployeeApp/EmployeeApp.AppHost/EmployeeApp.AppHost.csproj @@ -0,0 +1,24 @@ + + + + + + Exe + net8.0 + enable + enable + 1fd8c9f1-e232-4bc1-b971-029684372939 + + + + + + + + + + + + + + diff --git a/EmployeeApp/EmployeeApp.AppHost/Properties/launchSettings.json b/EmployeeApp/EmployeeApp.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..7426a8b --- /dev/null +++ b/EmployeeApp/EmployeeApp.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17236;http://localhost:15110", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21007", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22036" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15110", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19065", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20143" + } + } + } +} diff --git a/EmployeeApp/EmployeeApp.AppHost/appsettings.Development.json b/EmployeeApp/EmployeeApp.AppHost/appsettings.Development.json new file mode 100644 index 0000000..ff66ba6 --- /dev/null +++ b/EmployeeApp/EmployeeApp.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/EmployeeApp/EmployeeApp.AppHost/appsettings.json b/EmployeeApp/EmployeeApp.AppHost/appsettings.json new file mode 100644 index 0000000..2185f95 --- /dev/null +++ b/EmployeeApp/EmployeeApp.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/EmployeeApp/EmployeeApp.ServiceDefaults/EmployeeApp.ServiceDefaults.csproj b/EmployeeApp/EmployeeApp.ServiceDefaults/EmployeeApp.ServiceDefaults.csproj new file mode 100644 index 0000000..f40f4e1 --- /dev/null +++ b/EmployeeApp/EmployeeApp.ServiceDefaults/EmployeeApp.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/EmployeeApp/EmployeeApp.ServiceDefaults/Extensions.cs b/EmployeeApp/EmployeeApp.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..bf34b04 --- /dev/null +++ b/EmployeeApp/EmployeeApp.ServiceDefaults/Extensions.cs @@ -0,0 +1,127 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.ServiceDiscovery; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Microsoft.Extensions.Hosting; + +// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.ConfigureOpenTelemetry(); + + builder.AddDefaultHealthChecks(); + + builder.Services.AddServiceDiscovery(); + + builder.Services.ConfigureHttpClientDefaults(http => + { + // Turn on resilience by default + http.AddStandardResilienceHandler(); + + // Turn on service discovery by default + http.AddServiceDiscovery(); + }); + + // Uncomment the following to restrict the allowed schemes for service discovery. + // builder.Services.Configure(options => + // { + // options.AllowedSchemes = ["https"]; + // }); + + return builder; + } + + public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddSource(builder.Environment.ApplicationName) + .AddAspNetCoreInstrumentation(tracing => + // Exclude health check requests from tracing + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) + //.AddGrpcClientInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) + //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"])) + //{ + // builder.Services.AddOpenTelemetry() + // .UseAzureMonitor(); + //} + + return builder; + } + + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + // Add a default liveness check to ensure app is responsive + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + // Adding health checks endpoints to applications in non-development environments has security implications. + // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. + if (app.Environment.IsDevelopment()) + { + // All health checks must pass for app to be considered ready to accept traffic after starting + app.MapHealthChecks(HealthEndpointPath); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} diff --git a/README.md b/README.md index dcaa5eb..a105c84 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,38 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) +# Облачная разработка — Сервис генерации данных сотрудников -## Задание -### Цель -Реализация проекта микросервисного бекенда. +## Описание -### Задачи -* Реализация межсервисной коммуникации, -* Изучение работы с брокерами сообщений, -* Изучение архитектурных паттернов, -* Изучение работы со средствами оркестрации на примере .NET Aspire, -* Повторение основ работы с системами контроля версий, -* Интеграционное тестирование. +Микросервисное приложение для генерации данных сотрудников компании с кэшированием и балансировкой нагрузки. Оркестрация осуществляется при помощи .NET Aspire. -### Лабораторные работы -
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов -
- -В рамках первой лабораторной работы необходимо: -* Реализовать сервис генерации контрактов на основе Bogus, -* Реализовать кеширование при помощи IDistributedCache и Redis, -* Реализовать структурное логирование сервиса генерации, -* Настроить оркестрацию Aspire. - -
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы -
- -В рамках второй лабораторной работы необходимо: -* Настроить оркестрацию на запуск нескольких реплик сервиса генерации, -* Реализовать апи гейтвей на основе Ocelot, -* Имплементировать алгоритм балансировки нагрузки согласно варианту. +## Лабораторная работа №1 — Кэширование -
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда -
+### Что реализовано -В рамках третьей лабораторной работы необходимо: -* Добавить в оркестрацию объектное хранилище, -* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище, -* Реализовать отправку генерируемых данных в файловый сервис посредством брокера, -* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе. +- **Сервис генерации сотрудников** (`EmployeeApp.Api`) на основе библиотеки Bogus +- **Сущность `Employee`** с 10 полями: идентификатор, ФИО, должность, отдел, дата приёма, оклад, электронная почта, номер телефона, индикатор увольнения, дата увольнения +- **Генерация данных** с учётом пола (ФИО, отчество, фамилия), корреляции оклада с суффиксом должности, формата телефона `+7(***)***-**-**` +- **Кэширование** ответов через `IDistributedCache` и Redis +- **Структурное логирование** с помощью `ILogger` (логирование попаданий/промахов кэша, ошибок) +- **Оркестрация** через .NET Aspire (AppHost поднимает Redis, API и Redis Commander) +- **CORS** настроен для приёма запросов от клиента -
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud -
- -В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы: -* Клиент - в хостинг через отдельный бакет Object Storage, -* Сервис генерации - в Cloud Function, -* Апи гейтвей - в Serverless Integration как API Gateway, -* Брокер сообщений - в Message Queue, -* Файловый сервис - в Cloud Function, -* Объектное хранилище - в отдельный бакет Object Storage, +### Технологии -
-
+- .NET 8, Minimal API +- Bogus — генерация данных +- Redis — распределённый кэш +- .NET Aspire — оркестрация -## Задание. Общая часть -**Обязательно**: -* Реализация серверной части на [.NET 8](https://learn.microsoft.com/ru-ru/dotnet/core/whats-new/dotnet-8/overview). -* Оркестрация проектов при помощи [.NET Aspire](https://learn.microsoft.com/ru-ru/dotnet/aspire/get-started/aspire-overview). -* Реализация сервиса генерации данных при помощи [Bogus](https://github.com/bchavez/Bogus). -* Реализация тестов с использованием [xUnit](https://xunit.net/?tabs=cs). -* Создание минимальной документации к проекту: страница на GitHub с информацией о задании, скриншоты приложения и прочая информация. +## Лабораторная работа №2 — Балансировка нагрузки -**Факультативно**: -* Перенос бекенда на облачную инфраструктуру Yandex Cloud +### Что реализовано -Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью. -Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю. +- **API Gateway** на основе Ocelot с маршрутизацией запросов к бэкенду +- **5 реплик** сервиса `EmployeeApp.Api`, создаваемых в цикле через AppHost +- **Кастомный балансировщик нагрузки Query Based** — маршрутизация на основе параметра `id` из query string: `index = id % количество_реплик` +- **CORS** на Gateway настроен на приём только GET-запросов от клиента +- Gateway скрывает пути бэкенда через `UpstreamPathTemplate` -По итогу работы в семестре должна получиться следующая информационная система: -
-C4 диаграмма -Современные_технологии_разработки_ПО_drawio -
- -## Варианты заданий -Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи. - -[Список вариантов](https://docs.google.com/document/d/1WGmLYwffTTaAj4TgFCk5bUyW3XKbFMiBm-DHZrfFWr4/edit?usp=sharing) -[Список предметных областей и алгоритмов балансировки](https://docs.google.com/document/d/1PLn2lKe4swIdJDZhwBYzxqFSu0AbY2MFY1SUPkIKOM4/edit?usp=sharing) - -## Схема сдачи - -На каждую из лабораторных работ необходимо сделать отдельный [Pull Request (PR)](https://docs.github.com/en/pull-requests). - -Общая схема: -1. Сделать форк данного репозитория -2. Выполнить задание -3. Сделать PR в данный репозиторий -4. Исправить замечания после code review -5. Получить approve - -## Критерии оценивания - -Конкурентный принцип. -Так как задания в первой лабораторной будут повторяться между студентами, то выделяются следующие показатели для оценки: -1. Скорость разработки -2. Качество разработки -3. Полнота выполнения задания - -Быстрее делаете PR - у вас преимущество. -Быстрее получаете Approve - у вас преимущество. -Выполните нечто немного выходящее за рамки проекта - у вас преимущество. -Не укладываетесь в дедлайн - получаете минимально возможный балл. - -### Шкала оценивания - -- **3 балла** за качество кода, из них: - - 2 балла - базовая оценка - - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов: - - Реализация факультативного функционала - - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл - -## Вопросы и обратная связь по курсу - -Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](https://github.com/itsecd/cloud-development/discussions/categories/questions) или заведите [ишью](https://github.com/itsecd/cloud-development/issues/new). -Если у вас появились идеи/пожелания/прочие полезные мысли по преподаваемой дисциплине, их можно оставить [здесь](https://github.com/itsecd/cloud-development/discussions/categories/ideas). +### Алгоритм балансировки Query Based +От запрашиваемого идентификатора сотрудника находится остаток от деления по модулю числа реплик. Он определяет индекс реплики, которая обработает запрос.