Easy Setup for Parallel Test Execution with Selenium DockerSargis Sargsyan
Parallel execution of test cases is one of the important requirements of a modern test automation framework.
Generally, to run Selenium Suite in parallel, we use selenium grid and distributing tests across multiple machines which will reduce the time required for running tests. To run tests in parallel, we need to configure Selenium Grid with Hub and Nodes where the hub is the central point which will receive test requests along with configurations or capabilities. Based on the request received, the hub will distribute tests to the registered nodes.
Selenium has made a set of Docker images which are available on Docker Hub. We have Selenium Grid, and the browser images - Chrome and Firefox. There are also images with the debug versions which will let as view the test execution.
In this session, we will go through the Selenium tests parallel run setup and configuration.
Swarm in a nutshell
• Exposes several Docker Engines as a single virtual Engine
• Serves the standard Docker API
• Extremely easy to get started
• Batteries included but swappable
Pi Day 2022 - from IoT to MySQL HeatWave Database ServiceFrederic Descamps
HeatWave is a massively parallel, high performance, in-memory query accelerator for Oracle MySQL Database Service that accelerates MySQL performance by orders of magnitude for analytics and mixed workloads. But how do you collect data from an Internet of Things Environment so you can use HeatWave to process it? In one hour you will see how data collected by a Raspberry PI or other Internet of Things device can be uploaded to the MySQL Database Service and then processed by HeatWave.
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreC4Media
Video and slides synchronized, mp3 and slide download available at URL https://bit.ly/2rm4hFD.
Yevgeniy Brikman talks about how to write automated tests for infrastructure code, including the code written for use with tools such as Terraform, Docker, Packer, and Kubernetes. Topics covered include: unit tests, integration tests, end-to-end tests, dependency injection, test parallelism, retries and error handling, static analysis, property testing and CI / CD for infrastructure code. Filmed at qconsf.com.
Yevgeniy Brikman is the co-founder of Gruntwork, a company that provides DevOps as a Service. He is the author of two books published by O'Reilly Media: Hello, Startup and Terraform: Up & Running. Previously, he worked as a software engineer at LinkedIn, TripAdvisor, Cisco Systems, and Thomson Financial.
Infrastructure testing with Molecule and TestInfraTomislav Plavcic
Presentation defines what infrastructure as code is and what are some of the frameworks used for writing and testing it. More info is provided about Molecule framework which is used for testing Ansible roles and also TestInfra framework which can be used as a verifier with Molecule, but also as a standalone test framework.
Easy Setup for Parallel Test Execution with Selenium DockerSargis Sargsyan
Parallel execution of test cases is one of the important requirements of a modern test automation framework.
Generally, to run Selenium Suite in parallel, we use selenium grid and distributing tests across multiple machines which will reduce the time required for running tests. To run tests in parallel, we need to configure Selenium Grid with Hub and Nodes where the hub is the central point which will receive test requests along with configurations or capabilities. Based on the request received, the hub will distribute tests to the registered nodes.
Selenium has made a set of Docker images which are available on Docker Hub. We have Selenium Grid, and the browser images - Chrome and Firefox. There are also images with the debug versions which will let as view the test execution.
In this session, we will go through the Selenium tests parallel run setup and configuration.
Swarm in a nutshell
• Exposes several Docker Engines as a single virtual Engine
• Serves the standard Docker API
• Extremely easy to get started
• Batteries included but swappable
Pi Day 2022 - from IoT to MySQL HeatWave Database ServiceFrederic Descamps
HeatWave is a massively parallel, high performance, in-memory query accelerator for Oracle MySQL Database Service that accelerates MySQL performance by orders of magnitude for analytics and mixed workloads. But how do you collect data from an Internet of Things Environment so you can use HeatWave to process it? In one hour you will see how data collected by a Raspberry PI or other Internet of Things device can be uploaded to the MySQL Database Service and then processed by HeatWave.
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreC4Media
Video and slides synchronized, mp3 and slide download available at URL https://bit.ly/2rm4hFD.
Yevgeniy Brikman talks about how to write automated tests for infrastructure code, including the code written for use with tools such as Terraform, Docker, Packer, and Kubernetes. Topics covered include: unit tests, integration tests, end-to-end tests, dependency injection, test parallelism, retries and error handling, static analysis, property testing and CI / CD for infrastructure code. Filmed at qconsf.com.
Yevgeniy Brikman is the co-founder of Gruntwork, a company that provides DevOps as a Service. He is the author of two books published by O'Reilly Media: Hello, Startup and Terraform: Up & Running. Previously, he worked as a software engineer at LinkedIn, TripAdvisor, Cisco Systems, and Thomson Financial.
Infrastructure testing with Molecule and TestInfraTomislav Plavcic
Presentation defines what infrastructure as code is and what are some of the frameworks used for writing and testing it. More info is provided about Molecule framework which is used for testing Ansible roles and also TestInfra framework which can be used as a verifier with Molecule, but also as a standalone test framework.
Trabajo de fin de Ciclo Formativo Grado Superior en Administración de Sistemas en red (ASIR/ASIX).
El trabajo consiste en un proyecto de virtualizacion de servidores para dar una alta disponibilidad (HA) mediante el sistema Proxmox. El servicio a dar en cuestión finalmente fue de un servidor proxy y web, por falta de tiempo y problemas con la configuración de Zentyal, fue imposible su instalación.
Provides an overview of Redis which is a Key Value NoSQL database and the different data types it supports. Also shows how to use Redis Client API from node.
1. Overview
1.1 What is a web service?
1.2 What is a web service?(cont.)
2. Working with SOAP services
2.1 What is SOAP?
2.2 What is SOAP? (cont.)
2.3 Why is SOAP Needed?
2.4 SOAP Building Blocks
2.5 SOAP Building Blocks (cont.)
3. Working with XML
3.1 What is XML?
3.2 What is XML Parser?
3.3 The main types of parsers?
3.4 What is SAX parser?
3.5 What is SAX parser? (cont.)
3.6 What is DOM parser?
3.7 What is DOM parser? (cont.)
3.8 What is Pull parser?
3.9 What is Pull parser? (cont.)
4. Using KSoap2 Library
4.1 What is KSoap2?
4.2 Why is KSoap2 Needed?
5. Working with Restful web services
6. Working with JSON
6.1 What is JSON?
6.2 JSON’s basic types
Since its first 1.12 release on July 2016, Docker Swarm Mode has matured enough as a clustering and scheduling tool for IT administrators and developers who can easily establish and manage a cluster of Docker nodes as a single virtual system. Swarm mode integrates the orchestration capabilities of Docker Swarm into Docker Engine itself and help administrators and developers with the ability to add or subtract container iterations as computing demands change. With sophisticated but easy to implement features like built-in Service Discovery, Routing Mesh, Secrets, declarative service model, scaling of the services, desired state reconciliation, scheduling, filters, multi-host networking model, Load-Balancing, rolling updates etc. Docker 17.06 is all set for production-ready product today. Join me webinar organised by Docker Izmir, to get familiar with the current Swarm Mode capabilities & functionalities across the heterogeneous environments.
This talk is a very quick intro to Docker, Terraform, and Amazon's EC2 Container Service (ECS). In just 15 minutes, you'll see how to take two apps (a Rails frontend and a Sinatra backend), package them as Docker containers, run them using Amazon ECS, and to define all of the infrastructure-as-code using Terraform.
Lua: the world's most infuriating languagejgrahamc
Slides from a talk I gave at the Lua London Meetup on October 17: "When first confronted with Lua an experienced programmer (like me!) finds themselves infuriated by the languages little differences and hopes that can dismiss it as not worth learning :-) Later they find themselves infuriated to learn that they can't dismiss it: Lua is just too fast, too useful and too flexible. This talk will look at my experience of learning Lua and using it to send a high-altitude balloon into the stratosphere and build CloudFlare's new low latency WAF."
YouTube Link: https://youtu.be/sNxli6VwQTs
**DevOps Certification Courses - https://www.edureka.co/devops-certification-training**
This Edureka PPT on ‘Docker architecture’ will discuss the underlying architecture of Docker and the various components that constitute the architecture.
This PPT will focus on pointers like:
0:58 Traditional vs Docker
3:58 Docker Workflow
5:18 Docker Architecture
5:38 Docker Client
5:56 Docker Host
6:47 Docker Objects
11:11 Docker Registry
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Since the release of 17.05, Docker has introduced Multi-Stage Build for Docker Images for anyone who has struggled to optimize Dockerfiles while keeping them easy to read and maintain. This builder pattern will help anyone who would just like to have the runtime, configuration & application and doesn’t want to have compilers, debuggers, code, build, test logs etc.
Docker 101 is a series of workshops that aims to help developers (or interested people) to get started with docker.
The workshop 101 is were the audience has the first contact with docker, from installation to manage multiple containers.
- Installing docker
- managing images (docker rmi, docker pull)
- basic commands (docker info, docker ps, docker images, docker run, docker commit, docker inspect, docker exec, docker diff, docker stop, docker start)
- Docker registry
- container life cycle (running, paused, stopped, restarted)
- Dockerfile
In the *Day 01 Session* of the Flutter development our speaker *Mr. Sugheeshan* , who is *Flutter Development Associate at GDSC SKCT* will give an *Introduction to Flutter Basics*
Типовые проекты, где в центре системы стоит реляционная БД, перестают удовлетворять современным требованиям рынка ПО. В норму входит использование очередей, поисковых движков, NoSQL решений, облачных технологий. Всё это требует перехода от «классической» архитектуры к дроблению системы на набор низкосвязанных компонентов, взаимодействующих друг с другом через сообщения или интерфейсы.
Мы рассмотрим примеры типовых подходов и инструментов, которые сейчас актуальны в мире разработки масштабируемых систем.
Trabajo de fin de Ciclo Formativo Grado Superior en Administración de Sistemas en red (ASIR/ASIX).
El trabajo consiste en un proyecto de virtualizacion de servidores para dar una alta disponibilidad (HA) mediante el sistema Proxmox. El servicio a dar en cuestión finalmente fue de un servidor proxy y web, por falta de tiempo y problemas con la configuración de Zentyal, fue imposible su instalación.
Provides an overview of Redis which is a Key Value NoSQL database and the different data types it supports. Also shows how to use Redis Client API from node.
1. Overview
1.1 What is a web service?
1.2 What is a web service?(cont.)
2. Working with SOAP services
2.1 What is SOAP?
2.2 What is SOAP? (cont.)
2.3 Why is SOAP Needed?
2.4 SOAP Building Blocks
2.5 SOAP Building Blocks (cont.)
3. Working with XML
3.1 What is XML?
3.2 What is XML Parser?
3.3 The main types of parsers?
3.4 What is SAX parser?
3.5 What is SAX parser? (cont.)
3.6 What is DOM parser?
3.7 What is DOM parser? (cont.)
3.8 What is Pull parser?
3.9 What is Pull parser? (cont.)
4. Using KSoap2 Library
4.1 What is KSoap2?
4.2 Why is KSoap2 Needed?
5. Working with Restful web services
6. Working with JSON
6.1 What is JSON?
6.2 JSON’s basic types
Since its first 1.12 release on July 2016, Docker Swarm Mode has matured enough as a clustering and scheduling tool for IT administrators and developers who can easily establish and manage a cluster of Docker nodes as a single virtual system. Swarm mode integrates the orchestration capabilities of Docker Swarm into Docker Engine itself and help administrators and developers with the ability to add or subtract container iterations as computing demands change. With sophisticated but easy to implement features like built-in Service Discovery, Routing Mesh, Secrets, declarative service model, scaling of the services, desired state reconciliation, scheduling, filters, multi-host networking model, Load-Balancing, rolling updates etc. Docker 17.06 is all set for production-ready product today. Join me webinar organised by Docker Izmir, to get familiar with the current Swarm Mode capabilities & functionalities across the heterogeneous environments.
This talk is a very quick intro to Docker, Terraform, and Amazon's EC2 Container Service (ECS). In just 15 minutes, you'll see how to take two apps (a Rails frontend and a Sinatra backend), package them as Docker containers, run them using Amazon ECS, and to define all of the infrastructure-as-code using Terraform.
Lua: the world's most infuriating languagejgrahamc
Slides from a talk I gave at the Lua London Meetup on October 17: "When first confronted with Lua an experienced programmer (like me!) finds themselves infuriated by the languages little differences and hopes that can dismiss it as not worth learning :-) Later they find themselves infuriated to learn that they can't dismiss it: Lua is just too fast, too useful and too flexible. This talk will look at my experience of learning Lua and using it to send a high-altitude balloon into the stratosphere and build CloudFlare's new low latency WAF."
YouTube Link: https://youtu.be/sNxli6VwQTs
**DevOps Certification Courses - https://www.edureka.co/devops-certification-training**
This Edureka PPT on ‘Docker architecture’ will discuss the underlying architecture of Docker and the various components that constitute the architecture.
This PPT will focus on pointers like:
0:58 Traditional vs Docker
3:58 Docker Workflow
5:18 Docker Architecture
5:38 Docker Client
5:56 Docker Host
6:47 Docker Objects
11:11 Docker Registry
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Since the release of 17.05, Docker has introduced Multi-Stage Build for Docker Images for anyone who has struggled to optimize Dockerfiles while keeping them easy to read and maintain. This builder pattern will help anyone who would just like to have the runtime, configuration & application and doesn’t want to have compilers, debuggers, code, build, test logs etc.
Docker 101 is a series of workshops that aims to help developers (or interested people) to get started with docker.
The workshop 101 is were the audience has the first contact with docker, from installation to manage multiple containers.
- Installing docker
- managing images (docker rmi, docker pull)
- basic commands (docker info, docker ps, docker images, docker run, docker commit, docker inspect, docker exec, docker diff, docker stop, docker start)
- Docker registry
- container life cycle (running, paused, stopped, restarted)
- Dockerfile
In the *Day 01 Session* of the Flutter development our speaker *Mr. Sugheeshan* , who is *Flutter Development Associate at GDSC SKCT* will give an *Introduction to Flutter Basics*
Типовые проекты, где в центре системы стоит реляционная БД, перестают удовлетворять современным требованиям рынка ПО. В норму входит использование очередей, поисковых движков, NoSQL решений, облачных технологий. Всё это требует перехода от «классической» архитектуры к дроблению системы на набор низкосвязанных компонентов, взаимодействующих друг с другом через сообщения или интерфейсы.
Мы рассмотрим примеры типовых подходов и инструментов, которые сейчас актуальны в мире разработки масштабируемых систем.
Сегодня многие фреймворки, такие как Prism или Autofac, позволяют разработчику организовать модульную структуру приложения. При этом часто бывает непонятно, для чего ещё нужны модули, кроме как для пресловутой "красоты архитектуры".
В рамках доклада я расскажу о том, какие существуют подходы к организации модульной структуры, в каких фреймворках они реализованы и для решения каких задач дает преимущество каждый подход.
SERP или просто страница результатов поисковой выдачи — это действительно большой проект с огромной аудиторией. Над ним работают около 40 фронтендеров из разных городов. Эта страница показывается больше 200 000 000 раз в день. При таких размерах даже модульная архитектура уже не слишком спасала нас от странных, неочевидных зависимостей, лишних стилей и нескольких разных реализаций почти одинаковых компонентов.
Процесс разработки новой, даже довольно простой на первый взгляд фичи занимал чудовищное количество времени и представлял из себя хаотичное взаимодействие большого количества людей: фронта, бэкенда, дизайнеров и менеджеров.
Стала закрадываться мысль, что пора что-то менять. И мы поменяли.
В докладе я расскажу о том, как мы с помощью проекта на стыке фронтендеров, менеджеров, и дизайнеров, навели во всем этом идеальный порядок. Каким образом поменяли наш код процессы и инструменты, а также что нам это дало, и как будем жить с этим дальше.
Если вам знакомы похожие проблемы, то наш опыт может оказаться вам чертовски полезным.
В лекции рассказано о доступных средствах по отладке веб-сайтов, их возможностях, а также способах их использования. Также речь пойдет о том, как искать ошибки у пользователей в продакшене и контролировать качество продукта.
Инфраструктура для совместной предпроктной работы IT-компаний и реального ...Alexander Byndyu
Если у вас есть IT-компания и вы хотите делать проекты для промышленных предприятий, то предлагаю вам следующую схему, работоспособность которой мы проверили https://blog.byndyu.ru/2023/03/it.html
Выступление на конференции TrueTechDay 2023 в Москве.
Содержание:
1. Причины появления интереса к low-code платформам
2. Управление сложностью в обычном и low-code подходах
3. Технические проблемы с low-code и как снизить эти риски
4. Организационные проблемы с low-code и как снизить эти риски
5. Сценарии успешного применения
6. Чеклист выбора low-code платформы
Статья на эту тему и видео-запись доклада https://blog.byndyu.ru/2023/04/low-code.html
Если на переменах вы больше зарабатываете, чем теряете, вам будет хотеться перемен. В мире, где всё быстро меняется, где конкуренция возвышает одни компании и уничтожает другие, нужно выстраивать работу так, чтобы перемены приносили пользу, а не разрушения.
В докладе поразмышляем как выстроить процессы работы, архитектуру IT-систем и взаимодействия людей, чтобы придать IT-продуктам свойства антихрупкости.
https://13.codefest.ru/lecture/2251
Карта гипотез как метод стратегического планированияAlexander Byndyu
Расскажу о новом методе стратегического планирования. Много лет я смотрел, как другие делают Impact Map, сам его делал для своих проектов и проектов заказчиков. В итоге, пересобрал этот метод в новый, чтобы можно было точнее определять причинно-следственные связи между бизнес-целями, задачами и гипотезами достижения целей. Назвал этот метод “Карта гипотез”.
Доклад на конференции Стачка https://nastachku.ru/hypothesis-map-as-method-of-strategic-planning
История о том, как техническое задание подменяет цель проектаAlexander Byndyu
Видео на эту тему https://www.youtube.com/watch?v=fuy4Ol4nRNY
Писать или не писать ТЗ? В спорах на эту тему была сломана ни одна клавиатура. У нас есть свое мнение на счет технических заданий.
Рынок IT, привлечение разработчиков, выбор платформы и языка для разработки, выбор методологии управления, создание IT-продукта, IT-архитектура, современные возможности IT с примерами
— Как выявлять бизнес-цели
— Как согласовывать стратегию достижения целей
— Как приоритизировать бизнес-гипотезы
— Как использовать карту в работе над продуктом
— Влияние целей на мотивацию
— Как отсекать Pet Feature со стороны заказчика и со стороны команды
— Какие есть подводные камни в применении Impact Mapping + примеры из практики
CQRS на практике. В поиске точки масштабирования и новых метафор
1. CQRS на практике.
В поиске точки
масштабирования и новых
метафор
Александр Бындю
ByndyuSoft
2. 2
Обо мне
1. Владелец компании ByndyuSoft
http://byndyusoft.com
2. Консультант по вопросам разработки приложений и организации работы IT
компаний
3. Внештатный сотрудник Академии АйТи
4. Технический блог http://blog.byndyu.ru
5. Преподаю в ЮУрГУ и ЧелГУ
6. Тренер на AgileCamp
7. Организую конференции .NET-разработчиков
http://dotnetconf.ru
8. Веду группу по проблемам разработки приложений
https://groups.google.com/forum/?hl=ru&fromgroups#!forum/dotnetconf
3. 3
План
1. Основная теория CQRS
2. Эволюция кода
3. Эволюция архитектуры
4. Event Sourcing
5. Ограничения
6. Примеры реализации и подходы
6. 6
Command-query separation (CQS)
Методы объекта нужно разделить на:
1. Queries: Возвращают результат, не
изменяя состояние объекта
2. Commands: Изменяют состояние, не
возвращая значение.
free of side
effects
12. 12
Command
• Изменяет состояние системы
• Контекст команды хранит нужные для ее
выполнения данные
• Ничего не возвращает
• Хорошо описывает предметную область
13. 13
public class DeleteUserHandler : ICommandHandler<DeleteUser>
{
private readonly ISession session;
public DeleteUserHandler(ISession session)
{
this.session = session;
}
public void Execute(DeleteUser context)
{
session.Delete<User>(context.UserId);
}
}
14. 14
Query
1. Не изменяет состояние системы
2. Контекст запроса хранит нужные для ее
выполнения данные (пейджинг, фильтры
и т.п.)
3. Возвращает результат
free of side
effects
15. 15
public class FindUserByIdQuery : IQuery<FindById, User>
{
private readonly ISession session;
public FindUserByIdQuery(ISession session)
{
this.session = session;
}
public User Ask(FindById context)
{
return session.Query<User>()
.SingleOrDefault(x => x.Id == context.Id);
}
}
19. 19
Repository v2.0
Нужно больше методов
public class AccountRepository : IRepository<Account>
{
public IEnumerable<Account> GetActiveAccounts()
{
// ...
}
public void ChangeAccountAddress(int id, string newAddress)
{
// ...
}
public IEnumerable<Account> GetPremiumAccountsByManager()
{
// ...
20. 20
Repository v2.0
Нужно больше зависимостей
public class AccountRepository : IRepository<Account>
{
public AccountRepository(
IPriceCalculator priceCalculator,
IMessageDispatcher messageDispatcher,
IEmailSender emailSender,
IDataContext dataContext,
IAwsProvider awsProvider,
ISphinxProvider sphinxProvider,
IMongoDbProvider mongoDbProvider
/* ... */)
{
21. 21
Repository v3.0
Даешь IQueryable!
public class AccountRepository : IRepository<Account>
{
public IQueryable<Account> GetActiveAccounts()
{
// ...
}
public IQueryable<Account> GetPremiumAccountsByManager()
{
// ...
}
public Account GetAccountWithRoleInformation(int id)
{
// ...
}
24. 24
Repository v4.0
Предикаты условий выборки
public class ActiveAccountSpecification : ISpecification<Account>
{
public Func<Account, bool> IsSatisfiedBy()
{
return x => x.IsActive && x.Credit > 0;
}
}
25. 25
Repository v4.0
Стратегии подгрузки в отдельные классы
public class AccountCommentFetchStrategy : IFetchStrategy<Account>
{
public Action<Account> Apply()
{
return x => x.Posts.Select(p => p.Comments);
}
}
26. 26
Repository v4.0
public class AccountRepository : IRepository<Account>
{
public IEnumerable<Account> GetAccounts(
IFetchStrategy<Account>[] fetchStrategies,
ISpecification<Account>[] specifications)
{
// ...
}
Еще круче собирать их через
IoC-контейнер по конвенции
27. 27
Repository v5.0
Для изменения состояния системы работаем
с корнями агрегации.
Выборка данных для отображения собирает
DTO из разных частей данных.
28. 28
Repository v5.0
public class AccountRepository : IRepository<Account>
{
public IEnumerable<Account> GetActiveAccounts()
{
// ...
}
public void ChangeAccountAddress(int id, string newAddress)
{
// ...
}
public IEnumerable<Account> GetPremiumAccountsByManager()
{
// ...
}
ChangeAccountAddressCommand
GetActiveAccountsQuery
GetPremiumAccountsByManagerQuery
29. 29
public class FindPremiumAccountsByManagerQuery :
IQuery<FindPremiumAccountsByManager, User>
{
private readonly ISession session;
public FindPremiumAccountsByManagerQuery(ISession session)
{
this.session = session;
}
public User Ask(FindPremiumAccountsByManager context)
{
return session.Query<User>()…;
}
}
Отдельный класс из метода
31. 31
Маленькие объекты
1. Меньше зависимостей в каждом классе
2. SRP
3. Проще заменить
4. Проще тестировать
5. Делают дизайн кода однотипным
6. При расширении функциональности
системы сложность увеличивается (почти)
линейно
36. 36
Что делать?
1. Оптимизировать скрипты выборки
2. Убираем ORM для лучшей оптимизации
3. Убираем весь код выборки в хранимки
4. Оптимизируем индексы
5. Денормализуем данные
39. 39
Денормализация v3.0
Создать еще одну БД (хранилище) c
«плоскими» данными для чтения
1. Отдельная реляционная БД с «плоскими»
данными без связей
2. Различные NoSQL
3. Поисковые системы
51. 51
Предпосылки к Event Sourcing
1. Каким было состояние системы 2 недели
назад?
2. Имеете ли вы право затереть данные в
ячейке новыми?
3. Переходы между состояниями являются
частью бизнеса
53. 53
Event Sourcing
1. Все изменения записывать в виде дельты
2. Текущее состояние домена – это
проигрывание «журнала транзакций»
3. Построение проекций для выборок
4. Snapshot как оптимизация
55. 55
Надо ли мне Event Sourcing?
• Есть проблемы, которые не просто решить
– Как проектировать агрегаты?
– Как рефакторить агрегаты?
– Как изменять уже произошедшие события?
– Как накатываем события, которые зависели от
данных стороннего сервиса?
• Заказчики из разных прототипов не
выбирали ES
• Бизнесу не надо хранить всю историю
56. 56
5. Ограничения
1. Нужна подготовка, возможен bus
factor
2. Кто-то не любит много классов
3. Дублирование в маленьких классах
4. Сложно целиком придерживаться
CQS
5. Не всегда Eventually persisted
подходит UX в системе
58. 58
Пример вызова Query
public class FindUserById
{
public int Id { get; set; }
}
public class UserController : Controller
{
[HttpGet]
public ActionResult UserDetails(FindUserById context)
{
var dto = queryBuilder
.For<UserForEditDto>()
.With(context);
return View(dto);
}
59. 59
Пример вызова Command
public class EditUser
{
public int UserId { get; set; }
public string Name { get; set; }
}
public class UserController : Controller
{
[HttpPost]
public ActionResult Edit(EditUser context)
{
commandHander.Execute(context);
return this.RedirectToAction(x => x.List());
}
60. 60
Command Handler
public interface ICommandHandler<T> where T : ICommand
{
void Handle(T command);
}
public class EditUserCommandHandler : ICommandHandler<EditUser>
{
public void Execute(EditUser context)
{
// обновление данных
}
}
62. 62
Диспетчеризация через шину
public class HomeController : Controller
{
[HttpPost]
public ActionResult ChangeName(Guid id, string name, int version)
{
var command = new RenameInventoryItem(id, name, version);
bus.Send(command);
return RedirectToAction("Index");
}
63. 63
Диспетчеризация через шину
public class FakeBus : ICommandSender, IEventPublisher
{
public void Send<T>(T command) where T : Command
{
List<Action<Message>> handlers;
if (_routes.TryGetValue(typeof(T), out handlers))
{
if (handlers.Count != 1)
throw new InvalidOperationException();
handlers[0](command);
}
else
{
throw new InvalidOperationException("no handler registered");
}
}