FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
python-client/splitio/sync/segment.py at development · splitio/python-client · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
splitio
/
python-client
Public
Notifications
You must be signed in to change notification settings
Fork
13
Star
19
Code
Issues
4
Pull requests
5
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
python-client
/
splitio
/
sync
/
segment.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
646 lines (503 loc) · 24.1 KB
Breadcrumbs
python-client
/
splitio
/
sync
/
segment.py
Copy path
File metadata and controls
646 lines (503 loc) · 24.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
import
logging
import
time
import
json
import
os
from
splitio
.
api
import
APIException
from
splitio
.
api
.
commons
import
FetchOptions
from
splitio
.
tasks
.
util
import
workerpool
from
splitio
.
models
import
segments
from
splitio
.
util
.
backoff
import
Backoff
from
splitio
.
optional
.
loaders
import
asyncio
,
aiofiles
from
splitio
.
sync
import
util
from
splitio
.
util
.
storage_helper
import
get_standard_segment_names_in_rbs_storage
,
get_standard_segment_names_in_rbs_storage_async
from
splitio
.
optional
.
loaders
import
asyncio
_LOGGER
=
logging
.
getLogger
(
__name__
)
_ON_DEMAND_FETCH_BACKOFF_BASE
=
10
# backoff base starting at 10 seconds
_ON_DEMAND_FETCH_BACKOFF_MAX_WAIT
=
60
# don't sleep for more than 1 minute
_ON_DEMAND_FETCH_BACKOFF_MAX_RETRIES
=
10
_MAX_WORKERS
=
10
class
SegmentSynchronizer
(
object
):
def
__init__
(
self
,
segment_api
,
feature_flag_storage
,
segment_storage
,
rule_based_segment_storage
):
"""
Class constructor.
:param segment_api: API to retrieve segments from backend.
:type segment_api: splitio.api.SegmentApi
:param feature_flag_storage: Feature Flag Storage.
:type feature_flag_storage: splitio.storage.InMemorySplitStorage
:param segment_storage: Segment storage reference.
:type segment_storage: splitio.storage.SegmentStorage
"""
self
.
_api
=
segment_api
self
.
_feature_flag_storage
=
feature_flag_storage
self
.
_segment_storage
=
segment_storage
self
.
_rule_based_segment_storage
=
rule_based_segment_storage
self
.
_worker_pool
=
workerpool
.
WorkerPool
(
_MAX_WORKERS
,
self
.
synchronize_segment
)
self
.
_worker_pool
.
start
()
self
.
_backoff
=
Backoff
(
_ON_DEMAND_FETCH_BACKOFF_BASE
,
_ON_DEMAND_FETCH_BACKOFF_MAX_WAIT
)
def
recreate
(
self
):
"""
Create worker_pool on forked processes.
"""
self
.
_worker_pool
=
workerpool
.
WorkerPool
(
_MAX_WORKERS
,
self
.
synchronize_segment
)
self
.
_worker_pool
.
start
()
def
shutdown
(
self
):
"""
Shutdown worker_pool
"""
self
.
_worker_pool
.
stop
()
def
_fetch_until
(
self
,
segment_name
,
fetch_options
,
till
=
None
):
"""
Hit endpoint, update storage and return when since==till.
:param segment_name: Name of the segment to update.
:type segment_name: str
:param fetch_options Fetch options for getting segment definitions.
:type fetch_options splitio.api.FetchOptions
:param till: Passed till from Streaming.
:type till: int
:return: last change number
:rtype: int
"""
while
True
:
# Fetch until since==till
change_number
=
self
.
_segment_storage
.
get_change_number
(
segment_name
)
if
change_number
is
None
:
change_number
=
-
1
if
till
is
not
None
and
till
<
change_number
:
# the passed till is less than change_number, no need to perform updates
return
change_number
try
:
segment_changes
=
self
.
_api
.
fetch_segment
(
segment_name
,
change_number
,
fetch_options
)
except
APIException
as
exc
:
_LOGGER
.
error
(
'Exception raised while fetching segment %s'
,
segment_name
)
_LOGGER
.
debug
(
'Exception information: '
,
exc_info
=
True
)
raise
exc
if
change_number
==
-
1
:
# first time fetching the segment
new_segment
=
segments
.
from_raw
(
segment_changes
)
self
.
_segment_storage
.
put
(
new_segment
)
else
:
self
.
_segment_storage
.
update
(
segment_name
,
segment_changes
[
'added'
],
segment_changes
[
'removed'
],
segment_changes
[
'till'
]
)
if
segment_changes
[
'till'
]
==
segment_changes
[
'since'
]:
return
segment_changes
[
'till'
]
def
_attempt_segment_sync
(
self
,
segment_name
,
fetch_options
,
till
=
None
):
"""
Hit endpoint, update storage and return True if sync is complete.
:param segment_name: Name of the segment to update.
:type segment_name: str
:param fetch_options Fetch options for getting feature flag definitions.
:type fetch_options splitio.api.FetchOptions
:param till: Passed till from Streaming.
:type till: int
:return: Flags to check if it should perform bypass or operation ended
:rtype: bool, int, int
"""
self
.
_backoff
.
reset
()
remaining_attempts
=
_ON_DEMAND_FETCH_BACKOFF_MAX_RETRIES
while
True
:
remaining_attempts
-=
1
change_number
=
self
.
_fetch_until
(
segment_name
,
fetch_options
,
till
)
if
till
is
None
or
till
<=
change_number
:
return
True
,
remaining_attempts
,
change_number
elif
remaining_attempts
<=
0
:
return
False
,
remaining_attempts
,
change_number
how_long
=
self
.
_backoff
.
get
()
time
.
sleep
(
how_long
)
def
synchronize_segment
(
self
,
segment_name
,
till
=
None
):
"""
Update a segment from queue
:param segment_name: Name of the segment to update.
:type segment_name: str
:param till: ChangeNumber received.
:type till: int
:return: True if no error occurs. False otherwise.
:rtype: bool
"""
fetch_options
=
FetchOptions
(
True
,
spec
=
None
)
# Set Cache-Control to no-cache
successful_sync
,
remaining_attempts
,
change_number
=
self
.
_attempt_segment_sync
(
segment_name
,
fetch_options
,
till
)
attempts
=
_ON_DEMAND_FETCH_BACKOFF_MAX_RETRIES
-
remaining_attempts
if
successful_sync
:
# succedeed sync
_LOGGER
.
debug
(
'Refresh completed in %d attempts.'
,
attempts
)
return
True
with_cdn_bypass
=
FetchOptions
(
True
,
change_number
,
spec
=
None
)
# Set flag for bypassing CDN
without_cdn_successful_sync
,
remaining_attempts
,
change_number
=
self
.
_attempt_segment_sync
(
segment_name
,
with_cdn_bypass
,
till
)
without_cdn_attempts
=
_ON_DEMAND_FETCH_BACKOFF_MAX_RETRIES
-
remaining_attempts
if
without_cdn_successful_sync
:
_LOGGER
.
debug
(
'Refresh completed bypassing the CDN in %d attempts.'
,
without_cdn_attempts
)
return
True
_LOGGER
.
debug
(
'No changes fetched after %d attempts with CDN bypassed.'
,
without_cdn_attempts
)
return
False
def
synchronize_segments
(
self
,
segment_names
=
None
,
dont_wait
=
False
):
"""
Submit all current segments and wait for them to finish depend on dont_wait flag, then set the ready flag.
:param segment_names: Optional, array of segment names to update.
:type segment_name: {str}
:param dont_wait: Optional, instruct the function to not wait for task completion
:type segment_name: boolean
:return: True if no error occurs or dont_wait flag is True. False otherwise.
:rtype: bool
"""
if
segment_names
is
None
:
segment_names
=
set
(
self
.
_feature_flag_storage
.
get_segment_names
())
segment_names
.
update
(
get_standard_segment_names_in_rbs_storage
(
self
.
_rule_based_segment_storage
))
for
segment_name
in
segment_names
:
_LOGGER
.
debug
(
"Adding segment name to sync worker"
)
_LOGGER
.
debug
(
segment_name
)
self
.
_worker_pool
.
submit_work
(
segment_name
)
if
(
dont_wait
):
return
True
return
not
self
.
_worker_pool
.
wait_for_completion
()
def
segment_exist_in_storage
(
self
,
segment_name
):
"""
Check if a segment exists in the storage
:param segment_name: Name of the segment
:type segment_name: str
:return: True if segment exist. False otherwise.
:rtype: bool
"""
return
self
.
_segment_storage
.
get
(
segment_name
)
!=
None
class
SegmentSynchronizerAsync
(
object
):
def
__init__
(
self
,
segment_api
,
feature_flag_storage
,
segment_storage
,
rule_based_segment_storage
):
"""
Class constructor.
:param segment_api: API to retrieve segments from backend.
:type segment_api: splitio.api.SegmentApi
:param feature_flag_storage: Feature Flag Storage.
:type feature_flag_storage: splitio.storage.InMemorySplitStorage
:param segment_storage: Segment storage reference.
:type segment_storage: splitio.storage.SegmentStorage
"""
self
.
_api
=
segment_api
self
.
_feature_flag_storage
=
feature_flag_storage
self
.
_segment_storage
=
segment_storage
self
.
_rule_based_segment_storage
=
rule_based_segment_storage
self
.
_worker_pool
=
workerpool
.
WorkerPoolAsync
(
_MAX_WORKERS
,
self
.
synchronize_segment
)
self
.
_worker_pool
.
start
()
self
.
_backoff
=
Backoff
(
_ON_DEMAND_FETCH_BACKOFF_BASE
,
_ON_DEMAND_FETCH_BACKOFF_MAX_WAIT
)
def
recreate
(
self
):
"""
Create worker_pool on forked processes.
"""
self
.
_worker_pool
=
workerpool
.
WorkerPoolAsync
(
_MAX_WORKERS
,
self
.
synchronize_segment
)
self
.
_worker_pool
.
start
()
async
def
shutdown
(
self
):
"""
Shutdown worker_pool
"""
await
self
.
_worker_pool
.
stop
()
async
def
_fetch_until
(
self
,
segment_name
,
fetch_options
,
till
=
None
):
"""
Hit endpoint, update storage and return when since==till.
:param segment_name: Name of the segment to update.
:type segment_name: str
:param fetch_options Fetch options for getting segment definitions.
:type fetch_options splitio.api.FetchOptions
:param till: Passed till from Streaming.
:type till: int
:return: last change number
:rtype: int
"""
while
True
:
# Fetch until since==till
change_number
=
await
self
.
_segment_storage
.
get_change_number
(
segment_name
)
if
change_number
is
None
:
change_number
=
-
1
if
till
is
not
None
and
till
<
change_number
:
# the passed till is less than change_number, no need to perform updates
return
change_number
try
:
segment_changes
=
await
self
.
_api
.
fetch_segment
(
segment_name
,
change_number
,
fetch_options
)
except
APIException
as
exc
:
_LOGGER
.
error
(
'Exception raised while fetching segment %s'
,
segment_name
)
_LOGGER
.
debug
(
'Exception information: '
,
exc_info
=
True
)
raise
exc
if
change_number
==
-
1
:
# first time fetching the segment
new_segment
=
segments
.
from_raw
(
segment_changes
)
await
self
.
_segment_storage
.
put
(
new_segment
)
else
:
await
self
.
_segment_storage
.
update
(
segment_name
,
segment_changes
[
'added'
],
segment_changes
[
'removed'
],
segment_changes
[
'till'
]
)
if
segment_changes
[
'till'
]
==
segment_changes
[
'since'
]:
return
segment_changes
[
'till'
]
async
def
_attempt_segment_sync
(
self
,
segment_name
,
fetch_options
,
till
=
None
):
"""
Hit endpoint, update storage and return True if sync is complete.
:param segment_name: Name of the segment to update.
:type segment_name: str
:param fetch_options Fetch options for getting feature flag definitions.
:type fetch_options splitio.api.FetchOptions
:param till: Passed till from Streaming.
:type till: int
:return: Flags to check if it should perform bypass or operation ended
:rtype: bool, int, int
"""
self
.
_backoff
.
reset
()
remaining_attempts
=
_ON_DEMAND_FETCH_BACKOFF_MAX_RETRIES
while
True
:
remaining_attempts
-=
1
change_number
=
await
self
.
_fetch_until
(
segment_name
,
fetch_options
,
till
)
if
till
is
None
or
till
<=
change_number
:
return
True
,
remaining_attempts
,
change_number
elif
remaining_attempts
<=
0
:
return
False
,
remaining_attempts
,
change_number
how_long
=
self
.
_backoff
.
get
()
await
asyncio
.
sleep
(
how_long
)
async
def
synchronize_segment
(
self
,
segment_name
,
till
=
None
):
"""
Update a segment from queue
:param segment_name: Name of the segment to update.
:type segment_name: str
:param till: ChangeNumber received.
:type till: int
:return: True if no error occurs. False otherwise.
:rtype: bool
"""
fetch_options
=
FetchOptions
(
True
,
spec
=
None
)
# Set Cache-Control to no-cache
successful_sync
,
remaining_attempts
,
change_number
=
await
self
.
_attempt_segment_sync
(
segment_name
,
fetch_options
,
till
)
attempts
=
_ON_DEMAND_FETCH_BACKOFF_MAX_RETRIES
-
remaining_attempts
if
successful_sync
:
# succedeed sync
_LOGGER
.
debug
(
'Refresh completed in %d attempts.'
,
attempts
)
return
True
with_cdn_bypass
=
FetchOptions
(
True
,
change_number
,
spec
=
None
)
# Set flag for bypassing CDN
without_cdn_successful_sync
,
remaining_attempts
,
change_number
=
await
self
.
_attempt_segment_sync
(
segment_name
,
with_cdn_bypass
,
till
)
without_cdn_attempts
=
_ON_DEMAND_FETCH_BACKOFF_MAX_RETRIES
-
remaining_attempts
if
without_cdn_successful_sync
:
_LOGGER
.
debug
(
'Refresh completed bypassing the CDN in %d attempts.'
,
without_cdn_attempts
)
return
True
_LOGGER
.
debug
(
'No changes fetched after %d attempts with CDN bypassed.'
,
without_cdn_attempts
)
return
False
async
def
synchronize_segments
(
self
,
segment_names
=
None
,
dont_wait
=
False
):
"""
Submit all current segments and wait for them to finish depend on dont_wait flag, then set the ready flag.
:param segment_names: Optional, array of segment names to update.
:type segment_name: {str}
:param dont_wait: Optional, instruct the function to not wait for task completion
:type segment_name: boolean
:return: True if no error occurs or dont_wait flag is True. False otherwise.
:rtype: bool
"""
if
segment_names
is
None
:
segment_names
=
set
(
await
self
.
_feature_flag_storage
.
get_segment_names
())
segment_names
.
update
(
await
get_standard_segment_names_in_rbs_storage_async
(
self
.
_rule_based_segment_storage
))
self
.
_jobs
=
await
self
.
_worker_pool
.
submit_work
(
segment_names
)
if
(
dont_wait
):
return
True
return
await
self
.
_jobs
.
await_completion
()
async
def
segment_exist_in_storage
(
self
,
segment_name
):
"""
Check if a segment exists in the storage
:param segment_name: Name of the segment
:type segment_name: str
:return: True if segment exist. False otherwise.
:rtype: bool
"""
return
await
self
.
_segment_storage
.
get
(
segment_name
)
!=
None
class
LocalSegmentSynchronizerBase
(
object
):
"""Localhost mode segment base synchronizer."""
_DEFAULT_SEGMENT_TILL
=
-
1
def
_sanitize_segment
(
self
,
parsed
):
"""
Sanitize json elements.
:param parsed: segment dict
:type parsed: Dict
:return: sanitized segment structure dict
:rtype: Dict
"""
if
'name'
not
in
parsed
or
parsed
[
'name'
]
is
None
:
_LOGGER
.
warning
(
"Segment does not have [name] element, skipping"
)
raise
Exception
(
"Segment does not have [name] element"
)
if
parsed
[
'name'
].
strip
()
==
''
:
_LOGGER
.
warning
(
"Segment [name] element is blank, skipping"
)
raise
Exception
(
"Segment [name] element is blank"
)
for
element
in
[(
'till'
,
-
1
,
-
1
,
None
,
None
, [
0
]),
(
'added'
, [],
None
,
None
,
None
,
None
),
(
'removed'
, [],
None
,
None
,
None
,
None
)
]:
parsed
=
util
.
_sanitize_object_element
(
parsed
,
'segment'
,
element
[
0
],
element
[
1
],
lower_value
=
element
[
2
],
upper_value
=
element
[
3
],
in_list
=
None
,
not_in_list
=
element
[
5
])
parsed
=
util
.
_sanitize_object_element
(
parsed
,
'segment'
,
'since'
,
parsed
[
'till'
],
-
1
,
parsed
[
'till'
],
None
, [
0
])
return
parsed
class
LocalSegmentSynchronizer
(
LocalSegmentSynchronizerBase
):
"""Localhost mode segment synchronizer."""
def
__init__
(
self
,
segment_folder
,
feature_flag_storage
,
segment_storage
):
"""
Class constructor.
:param segment_folder: patch to the segment folder
:type segment_folder: str
:param feature_flag_storage: Feature flag Storage.
:type feature_flag_storage: splitio.storage.InMemorySplitStorage
:param segment_storage: Segment storage reference.
:type segment_storage: splitio.storage.SegmentStorage
"""
self
.
_segment_folder
=
segment_folder
self
.
_feature_flag_storage
=
feature_flag_storage
self
.
_segment_storage
=
segment_storage
self
.
_segment_sha
=
{}
def
synchronize_segments
(
self
,
segment_names
=
None
):
"""
Loop through given segment names and synchronize each one.
:param segment_names: Optional, array of segment names to update.
:type segment_name: {str}
:return: True if no error occurs. False otherwise.
:rtype: bool
"""
_LOGGER
.
info
(
'Synchronizing segments now.'
)
if
segment_names
is
None
:
segment_names
=
self
.
_feature_flag_storage
.
get_segment_names
()
return_flag
=
True
for
segment_name
in
segment_names
:
if
not
self
.
synchronize_segment
(
segment_name
):
return_flag
=
False
return
return_flag
def
synchronize_segment
(
self
,
segment_name
,
till
=
None
):
"""
Update a segment from queue
:param segment_name: Name of the segment to update.
:type segment_name: str
:param till: ChangeNumber received.
:type till: int
:return: True if no error occurs. False otherwise.
:rtype: bool
"""
try
:
fetched
=
self
.
_read_segment_from_json_file
(
segment_name
)
fetched_sha
=
util
.
_get_sha
(
json
.
dumps
(
fetched
))
if
not
self
.
segment_exist_in_storage
(
segment_name
):
self
.
_segment_sha
[
segment_name
]
=
fetched_sha
self
.
_segment_storage
.
put
(
segments
.
from_raw
(
fetched
))
_LOGGER
.
debug
(
"segment %s is added to storage"
,
segment_name
)
return
True
if
fetched_sha
==
self
.
_segment_sha
[
segment_name
]:
return
True
self
.
_segment_sha
[
segment_name
]
=
fetched_sha
if
self
.
_segment_storage
.
get_change_number
(
segment_name
)
>
fetched
[
'till'
]
and
fetched
[
'till'
]
!=
self
.
_DEFAULT_SEGMENT_TILL
:
return
True
self
.
_segment_storage
.
update
(
segment_name
,
fetched
[
'added'
],
fetched
[
'removed'
],
fetched
[
'till'
])
_LOGGER
.
debug
(
"segment %s is updated"
,
segment_name
)
except
Exception
as
e
:
_LOGGER
.
error
(
"Could not fetch segment: %s
\n
"
+
str
(
e
),
segment_name
)
return
False
return
True
def
_read_segment_from_json_file
(
self
,
filename
):
"""
Parse a segment and store in segment storage.
:param filename: Path of the file containing Feature flag
:type filename: str.
:return: Sanitized segment structure
:rtype: Dict
"""
try
:
with
open
(
os
.
path
.
join
(
self
.
_segment_folder
,
"%s.json"
%
filename
),
'r'
)
as
flo
:
parsed
=
json
.
load
(
flo
)
santitized_segment
=
self
.
_sanitize_segment
(
parsed
)
return
santitized_segment
except
Exception
as
exc
:
raise
ValueError
(
"Error parsing file %s. Make sure it's readable."
%
filename
)
from
exc
def
segment_exist_in_storage
(
self
,
segment_name
):
"""
Check if a segment exists in the storage
:param segment_name: Name of the segment
:type segment_name: str
:return: True if segment exist. False otherwise.
:rtype: bool
"""
return
self
.
_segment_storage
.
get
(
segment_name
)
!=
None
class
LocalSegmentSynchronizerAsync
(
LocalSegmentSynchronizerBase
):
"""Localhost mode segment async synchronizer."""
def
__init__
(
self
,
segment_folder
,
feature_flag_storage
,
segment_storage
):
"""
Class constructor.
:param segment_folder: patch to the segment folder
:type segment_folder: str
:param feature_flag_storage: Feature flag Storage.
:type feature_flag_storage: splitio.storage.InMemorySplitStorage
:param segment_storage: Segment storage reference.
:type segment_storage: splitio.storage.SegmentStorage
"""
self
.
_segment_folder
=
segment_folder
self
.
_feature_flag_storage
=
feature_flag_storage
self
.
_segment_storage
=
segment_storage
self
.
_segment_sha
=
{}
async
def
synchronize_segments
(
self
,
segment_names
=
None
):
"""
Loop through given segment names and synchronize each one.
:param segment_names: Optional, array of segment names to update.
:type segment_name: {str}
:return: True if no error occurs. False otherwise.
:rtype: bool
"""
_LOGGER
.
info
(
'Synchronizing segments now.'
)
if
segment_names
is
None
:
segment_names
=
await
self
.
_feature_flag_storage
.
get_segment_names
()
return_flag
=
True
for
segment_name
in
segment_names
:
if
not
await
self
.
synchronize_segment
(
segment_name
):
return_flag
=
False
return
return_flag
async
def
synchronize_segment
(
self
,
segment_name
,
till
=
None
):
"""
Update a segment from queue
:param segment_name: Name of the segment to update.
:type segment_name: str
:param till: ChangeNumber received.
:type till: int
:return: True if no error occurs. False otherwise.
:rtype: bool
"""
try
:
fetched
=
await
self
.
_read_segment_from_json_file
(
segment_name
)
fetched_sha
=
util
.
_get_sha
(
json
.
dumps
(
fetched
))
if
not
await
self
.
segment_exist_in_storage
(
segment_name
):
self
.
_segment_sha
[
segment_name
]
=
fetched_sha
await
self
.
_segment_storage
.
put
(
segments
.
from_raw
(
fetched
))
_LOGGER
.
debug
(
"segment %s is added to storage"
,
segment_name
)
return
True
if
fetched_sha
==
self
.
_segment_sha
[
segment_name
]:
return
True
self
.
_segment_sha
[
segment_name
]
=
fetched_sha
if
await
self
.
_segment_storage
.
get_change_number
(
segment_name
)
>
fetched
[
'till'
]
and
fetched
[
'till'
]
!=
self
.
_DEFAULT_SEGMENT_TILL
:
return
True
await
self
.
_segment_storage
.
update
(
segment_name
,
fetched
[
'added'
],
fetched
[
'removed'
],
fetched
[
'till'
])
_LOGGER
.
debug
(
"segment %s is updated"
,
segment_name
)
except
Exception
as
e
:
_LOGGER
.
error
(
"Could not fetch segment: %s
\n
"
+
str
(
e
),
segment_name
)
return
False
return
True
async
def
_read_segment_from_json_file
(
self
,
filename
):
"""
Parse a segment and store in segment storage.
:param filename: Path of the file containing Feature flag
:type filename: str.
:return: Sanitized segment structure
:rtype: Dict
"""
try
:
async
with
aiofiles
.
open
(
os
.
path
.
join
(
self
.
_segment_folder
,
"%s.json"
%
filename
),
'r'
)
as
flo
:
parsed
=
json
.
loads
(
await
flo
.
read
())
santitized_segment
=
self
.
_sanitize_segment
(
parsed
)
return
santitized_segment
except
Exception
as
exc
:
raise
ValueError
(
"Error parsing file %s. Make sure it's readable."
%
filename
)
from
exc
async
def
segment_exist_in_storage
(
self
,
segment_name
):
"""
Check if a segment exists in the storage
:param segment_name: Name of the segment
:type segment_name: str
:return: True if segment exist. False otherwise.
:rtype: bool
"""
return
await
self
.
_segment_storage
.
get
(
segment_name
)
!=
None
Back
|
FazBrowse Home
|
New Git URL