Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Choose single result (based on priority & weight) #11

Open
OJFord opened this issue Jul 1, 2022 · 1 comment
Open

Choose single result (based on priority & weight) #11

OJFord opened this issue Jul 1, 2022 · 1 comment

Comments

@OJFord
Copy link

OJFord commented Jul 1, 2022

I think it'd be nice to add a function (and perhaps use if __name__ == '__main__' too?) that return a single host:port from among the resolved options, according to their priority and weight.

I'd be happy to work a PR if you're interested.

@OJFord
Copy link
Author

OJFord commented Jul 1, 2022

Just as a proof of concept, something like:

import random
from sys import argv
from srvlookup import lookup


def choose_srv(*args):
    srvs = lookup(*args)

    top_priority_srvs = []
    total_weight = 0
    for srv in srvs:
        if srv.priority == srvs[0].priority:
            top_priority_srvs.append(srv)
            total_weight += srv.weight

    return random.choices(
        population=top_priority_srvs,
        weights=(srv.weight / total_weight for srv in top_priority_srvs),
        k=1,
    )[0]


if __name__ == "__main__":
    args = argv[1:]
    if len(args) == 1:
        args = args[0].split(".", 2)
        for i, arg in enumerate(args[:2]):
            args[i] = arg.lstrip("_")

    srv = choose_srv(*args)
    print(f"{srv.host}:{srv.port}")

Which can then be used as:

curl $(choose-srv _some._thing.foo.bar)

or whatever.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant