-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathld_demo.py
More file actions
154 lines (121 loc) · 6.4 KB
/
ld_demo.py
File metadata and controls
154 lines (121 loc) · 6.4 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
import os
import time
from dotenv import load_dotenv
import ldclient
from ldclient.config import Config
from ldclient import Context
# ── SDK setup ─────────────────────────────────────────────────────────────────
load_dotenv()
SDK_KEY = os.environ.get("LAUNCHDARKLY_SDK_KEY")
if not SDK_KEY:
raise SystemExit("Set LAUNCHDARKLY_SDK_KEY in your .env file.")
ldclient.set_config(Config(SDK_KEY))
client = ldclient.get()
# ── User pool for rollout demos ────────────────────────────────────────────────
# Segment membership is managed in LaunchDarkly — no custom attributes needed.
# Carol (ak_user-003) and Grace (ak_user-007) are in the "premium-users" segment.
ROLLOUT_USERS = [
{"key": "ak_user-001", "name": "Alice"},
{"key": "ak_user-002", "name": "Bob"},
{"key": "ak_user-003", "name": "Carol"}, # in segment: premium-users
{"key": "ak_user-004", "name": "David"},
{"key": "ak_user-005", "name": "Eva"},
{"key": "ak_user-006", "name": "Frank"},
{"key": "ak_user-007", "name": "Grace"}, # in segment: premium-users
{"key": "ak_user-008", "name": "Henry"},
{"key": "ak_user-009", "name": "Iris"},
{"key": "ak_user-010", "name": "James"},
]
def build_context(user: dict) -> Context:
# Context only needs kind + key — segment membership is evaluated server-side in LD.
return (
Context.builder(user["key"])
.kind("user")
.name(user["name"])
.build()
)
def choose_user():
print("1 Early Access User (in segment: premium-users)")
print("2 General User (not in segment)")
choice = input("Choose (1 or 2): ").strip()
if choice == "1":
user = {"key": "ak_user-003", "name": "Carol"}
else:
user = {"key": "ak_user-001", "name": "Alice"}
return build_context(user), user
# ── Demo 1: targeting ──────────────────────────────────────────────────────────
def demo_targeting(context: Context, user: dict) -> None:
print(f"\nContext: key={user['key']} name={user['name']}")
# Evaluate the flag for this context.
# Fallback (False) is returned only if the SDK can't reach LaunchDarkly.
result = client.variation("disable-payments", context, False)
# Toggle this flag ON in LaunchDarkly to simulate an incident response.
# true = server blocks payment, returns 503 maintenance response
# false = server processes payment normally
print(f"disable-payments → {result} ({'BLOCKED — returning 503' if result else 'ENABLED — processing payment'})")
# ── Demo 2: percentage rollout ─────────────────────────────────────────────────
def demo_percentage_rollout() -> None:
# Set the flag's default rule to a percentage rollout in LaunchDarkly,
# then press Enter. Each user key hashes to a 0–99 bucket — deterministic.
print("\nGo to LaunchDarkly → release-checkout-redesign → set default rule to a % rollout → save")
input("Press Enter when done — script will read the live value from LD: ")
print(f"\n{'Name':<10} {'Segment':<16} {'Result'}")
print("-" * 42)
new_count = 0
for user in ROLLOUT_USERS:
context = build_context(user)
gets_new = client.variation("release-checkout-redesign", context, False)
segment = "premium-users" if user["key"] in ("ak_user-003", "ak_user-007") else "—"
print(f"{user['name']:<10} {segment:<16} {'new UI' if gets_new else 'old UI'}")
if gets_new:
new_count += 1
total = len(ROLLOUT_USERS)
print(f"\n{new_count}/{total} users on new UI")
# ── Demo 3: gradual rollout ────────────────────────────────────────────────────
def demo_gradual_rollout() -> None:
steps = [
("10% — canary", "Go to LaunchDarkly → set default rule to 10% → save"),
("50% — broad beta", "Go to LaunchDarkly → increase to 50% → save"),
("100% — full launch", "Go to LaunchDarkly → increase to 100% → save"),
]
for label, instruction in steps:
print(f"\n{label}")
print(f" Action: {instruction}")
input(" Press Enter when done — script will read the live value from LD: ")
new_count = 0
reached = []
for user in ROLLOUT_USERS:
context = build_context(user)
gets_new = client.variation("release-checkout-redesign", context, False)
if gets_new:
new_count += 1
reached.append(user["name"])
total = len(ROLLOUT_USERS)
print(f"{new_count}/{total} users on new UI — {', '.join(reached) if reached else 'none yet'}")
# After 7 days at 100%, flag status becomes "Launched" in LD →
# signal to remove the flag wrapper from code and archive the flag.
print("\nRollout complete. Next: remove flag from code, archive in LaunchDarkly.")
# ── Main menu ──────────────────────────────────────────────────────────────────
def run_demo() -> None:
time.sleep(1) # allow SDK to fully initialize
if not client.is_initialized():
print("WARNING: SDK not initialized — check your SDK key.")
print("\n1 Targeting (evaluate flag for a chosen user)")
print("2 Percentage rollout (evaluate across 10 users)")
print("3 Gradual rollout (step through 10% → 50% → 100%)")
choice = input("\nChoose (1 / 2 / 3): ").strip()
if choice == "2":
demo_percentage_rollout()
elif choice == "3":
demo_gradual_rollout()
else:
# Flag: disable-payments
# Type: Boolean | true = block payment, return 503 | false = process normally
# Toggle ON/OFF in LaunchDarkly during the demo — no redeploy needed
context, user = choose_user()
demo_targeting(context, user)
if __name__ == "__main__":
try:
run_demo()
finally:
client.close()