-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathkeeping-software-soft.pug
More file actions
461 lines (441 loc) · 22.1 KB
/
keeping-software-soft.pug
File metadata and controls
461 lines (441 loc) · 22.1 KB
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
doctype html
html
head
meta(charset="utf-8")
meta(name="description" content="Keeping Software Soft")
meta(name="author" content="Artem Malyshev")
meta(name="apple-mobile-web-app-capable" content="yes")
meta(name="apple-mobile-web-app-status-bar-style" content="black-translucent")
meta(name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")
title Keeping Software Soft
body
.reveal
.slides
section
h2 Keeping Software Soft
h4
a(href="https://github.com/proofit404") Artem Malyshev
h6
a(href="https://twitter.com/proofit404") @proofit404
section(data-background-image=require("./pics/martin-fowler.jpg").default data-background-size="contain" data-background-position="right" data-background-color="#000000")
br
section
h2 BIO
ul
li Co-Founder at #[a(href="https://drylabs.io/") drylabs.io]
li #[a(href="https://dry-python.org/") dry-python.org]
li Django Channels 1.0
li 5 years of experience in Python
section(data-background-image=require("./pics/startup-process.png").default data-background-size="contain" data-background-color="#2E677B")
br
section(data-background-image=require("./pics/reading-other-peoples-code.png").default data-background-size="contain")
br
section
img(src=require("./pics/flask.png").default height="100" style=" padding-right: 70px;").plain
img(src=require("./pics/express.png").default height="100" style=" padding-right: 70px;").plain
img(src=require("./pics/sinatra.png").default height="100" style=" padding-right: 70px;").plain
aside.notes
p несторуктурированный проект на фласке синатре
section(data-background-image=require("./pics/long-function.jpg").default data-background-size="contain")
br
aside.notes
p тут мы json валидируем
p тут мы в базу ходим
p а тут в письма рассылаем
p всё в функциях по 1000 строк кода
section
h2 pros
ol
li.fragment Relatively easy to read
h2.fragment cons
ol
li.fragment Really hard to change
li.fragment We can not see the whole picture
aside.notes
p в результате
p легко читать
p тяжело менять
p чтобы добавить какую-нибудь фигню надо перелопатить весь проект
section
img(src=require("./pics/django.png").default height="100" style=" padding-right: 70px;").plain
img(src=require("./pics/ruby-on-rails.png").default height="100" style=" padding-right: 70px;").plain
img(src=require("./pics/spring.png").default height="100" style=" padding-right: 70px;").plain
aside.notes
p eсть стартапы с django rails nestjs spring
p там за людей уже подумали как структурировать код
p казалось бы решение проблемы
section(data-background-image=require("./pics/trello-issue.png").default data-background-size="contain" data-background-color="#002B45")
br
aside.notes
p вот приходишь ты в такой стартап, получаешь таску
p идёшь в код
section
h2 Implicit API
pre
code.python.
class Purchases(viewsets.ModelViewSet):
queryset = Purchase.objects.all()
serializer_class = PurchaseSerializer
permission_classes = (CanPurchase,)
filter_class = PurchaseFilter
pre
code.python.
router.register('/api/purchases/', Purchases)
ol
li.fragment What exactly does this class do?
li.fragment How to use it?
section(data-background-image=require("./pics/method-flowchart.png").default data-background-size="contain")
br
section
h2 Function to change
pre
code.python.
from google_cloud_messaging import send_message
@observer
def send_sms(event):
text = 'You purchase something!'
on_commit(lambda: send_message(text))
img(src=require("./pics/grep-test.png").default).fragment.plain
aside.notes
p В документации нет ни слова про вызов нашей функции
p Не ясно как передать в неё нужные нам аргументы
section
h2 pros
ol
li.fragment Relatively easy to change
h2.fragment cons
ol
li.fragment Really hard to read
li.fragment You should keep in mind framework rules
li.fragment Implicit knowledge grow
li.fragment We still can not see the whole picture
aside.notes
p тяжело читать
p проще править
p надо держать в голове полную картину работы фреймворка
section(data-background-image=require("./pics/lost-in-translation.jpg").default data-background-size="contain")
br
aside.notes
p в каждом примере мы понятия не имеем что вообще делает наше приложение
p это может быть и бложек и торговая площадка
p наши проекты не имеют связи в внешним миром
p очень много неявных знаний в головах разработчиках
section
h2 Business-friendly tools
pre
code.gherkin.
Scenario: Publishing the article
Given I am an author user
And I have an article
When I go to the article page
pre.fragment
code.python.
@given('I am an author user')
def author_user(ctx):
ctx['user'] = Author()
@given('I have an article')
def article(ctx):
ctx['article'] = create_article(author=ctx['user'])
@when('I go to the article page')
def go_to_article(ctx):
Browser().visit(f"/articles/{ctx['article'].id}/")
section
h2 pros
ol
li.fragment Clean flow in the source code
li.fragment Separate step implementation
li.fragment Each step knows nothing about a neighbor
li.fragment Easy reuse of code
h2.fragment cons
ol
li.fragment Does not relate to programming so much
aside.notes
p какое у них свойство?
p весь воркфлоу описан на понятном человеческом языке отдельно от реализации
p реализация каждого шага ничего не знает про соседний
p соответственно шаги легко переиспользовать в любом порядке
p их легко менять
section(data-background-image=require("./pics/eric-evans.jpg").default data-background-size="contain" data-background-position="left" data-background-color="#000000")
br
aside.notes
p что такое ddd
p ддд есть а инструментов не так много
section
img(src=require("./pics/trailblazer.png").default height="100" style=" padding-right: 70px;").plain
img(src=require("./pics/dry-rb.png").default height="100" style=" padding-right: 70px;").plain
img(src=require("./pics/hanami.png").default height="100" style=" padding-right: 70px;").plain
img(src="https://raw.githubusercontent.com/dry-python/brand/master/logo/dry-python.png" height="100" style=" padding-right: 70px;").plain
section
h2
a(href="https://dry-python.org/") dry-python
p A set of libraries for pluggable business logic components.
img(src="https://raw.githubusercontent.com/dry-python/brand/master/logo/dry-python.png").plain
aside.notes
p мы начали пилить dry-python
p набор библиотек, который навязывает писать бизнеслогику
section
img(src="https://raw.githubusercontent.com/dry-python/brand/master/logo/stories.png").plain
p Define a user story in the business transaction DSL.
p Separate state, implementation and specification.
section
h2 Specification DSL
pre
code.python.
from stories import story, arguments
class Purchase:
@story
@arguments("invoice_id", "user")
def buy(I):
I.find_order
I.find_price
I.find_invoice
I.check_balance
I.persist_payment
I.persist_purchase
I.send_purchase_notification
aside.notes
p пример dsl
p именно dsl начали делать больше случайно
p но потом получили профиты (о них дальше)
p это работает ...
section
h2 Steps implementation
pre
code.python.
from stories import Failure, Success
class Purchase:
# ...
def find_invoice(self, ctx):
invoice = Invoice.objects.get(pk=ctx.invoice_id)
return Success(invoice=invoice)
def check_balance(self, ctx):
if ctx.user.can_pay(ctx.invoice):
return Success()
else:
return Failure()
aside.notes
p пример реализации шагов
p решение:
p начали отвязывать код того проекта написанного на обсерверах
p мы так же получили раздельные шаги с хорошым переиспользованием
p DDD - тот самый ясный язык
section
img(src=require("./pics/postgresql.png").default height="100" style=" padding-right: 70px;").plain
img(src=require("./pics/firebase.png").default height="100" style=" padding-right: 70px;").plain
aside.notes
p жили не тужили всё было хорошо
p всё было в постгресе
p все данные и правила с ними связанные в realtion mapper
p пришёл бизнес
p сказал что так-то так-то интегрируемся переезжаем
p половина данных переехала в firebase
section
h2 Problems
h4 We do not have the tooling to work with data
h4 There are no data contracts written in code
aside.notes
p в результате отвалилась вся возможность работы с данными
p проблема: нет явно прописанных правил о данных, которыми живёт проект
p DDD: нет модели
section
img(src=require("./pics/attrs.png").default height="100" style=" padding-right: 70px;").plain
img(src=require("./pics/dry-rb.png").default height="100" style=" padding-right: 70px;").plain
img(src=require("./pics/lombok.png").default height="100" style=" padding-right: 70px;").plain
aside.notes
p attrs/dataclasses dry-structures lombok
section
h2 dataclasses
pre
code.python.
from dataclasses import dataclass
from typing import List, NewType
OrderId = NewType("OrderId", int)
@dataclass
class LineItem:
product_id: ProductId
@dataclass
class Order:
primary_key: OrderId
items: List[LineItem]
aside.notes
p начали прописывать в этих самых датаклассах контракты данных
section
h2 State Contract
pre
code.python.
from pydantic import BaseModel
class Purchase:
@story
def buy(I):
...
@Purchase.buy.contract
class Context(BaseModel):
user: User
invoice_id: InvoiceId
invoice: Optional[Invoice]
aside.notes
p захотелось чтобы рантайм проверял эти контракты во время попадания этих переменных в контекст
p а не писать эти проверки как часть сценариев каждый раз
section
h2 pros
ol
li.fragment Explicit data contracts and relations in code
li.fragment Data store independent
li.fragment Catch errors when they occur
li.fragment Not when they propagate to exception
h2.fragment cons
ol
li.fragment Working with data sources manually
aside.notes
p уныло перегонять руками таблички бд и ответы api в нормальное представление
p решение: писать логику отвязанной от data store implementation
section
img(src="https://raw.githubusercontent.com/dry-python/brand/master/logo/mappers.png").plain
p Declarative mappers from ORM models to domain entities. And back again!
aside.notes
p начали писать мапперс
p умеем в django, sqlalchemy, swagger, graphql
section
h2 Django ORM
pre
code.python.
from mappers import Mapper
from app.aggregates import Order, OrderId, User
from app.models import OrderModel, UserModel
mapper = Mapper(Order, OrderModel, {"primary_key": "pk"})
@mapper.reader
def load_order(id: OrderId, user: User) -> Order:
friends = UserModel.objects.filter(
purchases=OuterRef("pk"), friends=user.primary_key)
return OrderModel.objects.filter(pk=id).annotate(
purchased_by_friends=Exists(friends)).get()
section
h2 Swagger definitions
pre
code.python.
from mappers import Mapper
from bravado import swagger_model
from app.aggregates import Price
spec = swagger_model.load_file("price_service.yml")
mapper = Mapper(Price, spec.definitions["Price"])
@mapper.reader
def load_price(id: PriceId) -> Price:
return requests.get(f"http://172.16.1.7/get/{id}")
section
h2 GraphQL queries
pre
code.python.
from mappers import Mapper
from gql import gql, Client, build_schema
from app.models import Invoice
schema = build_schema("invoice_service.graphql")
mapper = Mapper(Invoice, schema.get_type_map()["Invoice"])
@mapper.reader
def load_invoice(id: InvoiceId) -> Invoice:
return Client(schema=schema).execute(gql("""
{
loadInvoice(id: %(id)d)
}
""", {"id": id}))
section
img(src=require("./pics/pusher.png").default).plain
aside.notes
p жили не тужили
p был у нас пушер
p пушер это ...
section
h2 How to use third-party library
pre
code.python.
from pusher import Pusher
class Purchase:
def send_purchase_notification(ctx):
Pusher().trigger("private-user-1")
pre
code.python.
def test_before(monkeypatch):
monkeypatch.setattr(pusher, "Pusher", Mock())
# ...
pusher.Pusher.trigger.assert_called_once_with(
"private-user-1"
)
aside.notes
p как обычно используют сторонние библиотеки в проекте?
p импортируем на прямую пихаем им данные так как они того хотят
p в тестах stubим библиотеку и ассертим данные которые им скормили
section
img(src=require("./pics/ably.png").default).plain
aside.notes
p пришёл бизнес
p хотим горантию доставки сообщений
p переезжаем на ably
section
h2 How to use it with DI
pre
code.python.
class Purchase:
def send_purchase_notification(ctx):
self.trigger_message(UserStream(ctx.user))
trigger_message: Emitter
pre
code.python.
def test_after(emitter):
# ...
Purchase.trigger_message.assert_called_once_with(
UserStream(User(primary_key=1))
)
aside.notes
p да у них даже апи похоже
p только вот у нас в шагах всё шурупами прикручено к pusher
p давайте ходить по всему проекту менять - на :
p а ещё как будто этого мало поменяем полмилиона ассертов в тастах
p мы расширили модель данных до stream и event
p добавили интерфейсов для посылки сообщений
p пропихнули их через DI в сториз
p переписали asserts на stream и event
p реализовали новый интерфейс на ably
p как же мне полегчало когда 2 недели после этого мы навыкатывали новых фич
p в пятницу вечером опять пришёл бизнес
p "фронтендеры не успевают переехать на ably, откатываем на pusher, но чтоб все фичи за 2 недели были"
p Я говорю - 5 минут делов
p была проблема - внутри шагов всё привязано конкретным сторонним библиотекам
p решение - интерфейсы нас спасут
p предотвратят от протекания ограничений конкретной тулзы в бизнес логики
section(data-background-image=require("./pics/debug-toolbar.png").default data-background-size="contain")
h2 DEBUG TOOLBAR
br
br
br
br
br
br
br
br
br
br
aside.notes
p жили не тужили
p но чего-то не хватало
p запилили интеграцию с debug toolbar потомучто сценарий падал на шаге без описания по какой бизнес логике прошёл
section(data-background-image=require("./pics/pytest.png").default data-background-size="contain")
h2(style="color: white") py.test
aside.notes
p кто ломал сиай?
p отычно тесты падают assertion error true is not false
p спасибо помог!
p мы напилили интеграцию с test frameworks чтобы показыват какая строчка теста чего выполняла
section(data-background-image=require("./pics/sentry.png").default data-background-size="contain")
h2 Sentry
aside.notes
p напилили интеграцию с sentry
section(data-background-image=require("./pics/elk-logs-ui.gif").default data-background-size="contain")
h2 ELK
aside.notes
p напилим интеграцию с elk
section(data-background-image=require("./pics/keep-calm-and-ddd.png").default data-background-size="contain" data-background-color="#C10C06")
br
aside.notes
p подитожим
p было большое приложение с месивом из хаков
p получили меньшее приложение с ясной картиной мира
p соглашения не работаят, работают инструменты