Created
December 1, 2016 16:54
-
-
Save bitglue/0b120f6c10f85c613a58b34d46698d7f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import time | |
import random | |
from functools import wraps | |
def microservice(f): | |
@wraps(f) | |
def wrapper(*args, **kwargs): | |
# Network connections require RAM, | |
x = list(range(1000)) | |
# and CPU overhead. | |
for _ in x: | |
_ = 42 * x | |
# Networks are slow. Sometimes *really* slow. | |
time.sleep(random.expovariate(10)) | |
if random.randint(1, 100) == 1: | |
time.sleep(900) | |
# Networks are unpredictible. | |
choices = [] | |
# Sometimes everything works. | |
def run(): | |
return f(*args, **kwargs) | |
choices.append(run) | |
# Sometimes, they work even though it looks like they didn't. | |
def run(): | |
f(*args, **kwargs) | |
while True: | |
time.sleep(300) | |
choices.append(run) | |
# Sometimes, the service at the other end has changed and it no longer | |
# does what you expect.. | |
def run(): | |
return g(*args, **kwargs) | |
choices.append(run) | |
# For some protocols, your message can be delivered more than once. | |
def run(): | |
f(*args, **kwargs) | |
f(*args, **kwargs) | |
f(*args, **kwargs) | |
return f(*args, **kwargs) | |
choices.append(run) | |
# You can run out of TCP ports, file descriptiors, or exhaust any | |
# number of other resources. | |
def run(): | |
raise OSError | |
choices.append(run) | |
# Network failures can mean failures never get reported to you, | |
def run(): | |
try: | |
return f(*args, **kwargs) | |
except: | |
return None | |
choices.append(run) | |
# but when the failures do make it back, they are usually pretty opaque. | |
def run(): | |
try: | |
return f(*args, **kwargs) | |
except: | |
return Exception(500) | |
choices.append(run) | |
# But you never know which of these things will happen! | |
return random.choice(choices)() | |
return wrapper | |
# But if you have a good reason, a service can still be a net win. | |
@microservice | |
def message(): | |
return "hello microservice world!" | |
# Have fun! | |
if __name__ == '__main__': | |
print(message()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment