Repository navigation
Expand file tree
/
Copy pathcontroller.py
More file actions
84 lines (74 loc) · 2.95 KB
/
Copy pathcontroller.py
File metadata and controls
84 lines (74 loc) · 2.95 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
# Copyright (c) 2022-2026 Super Durable, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import random
from dex import FlowNotActiveOrNotFoundError
from quart import Blueprint, Response, jsonify
from dex_examples.app import ExampleApp
from dex_examples.config import start_options
from dex_examples.patterns.resource_control.controller_flow import (
SPOT_INSTANCE_IDS,
ControllerFlow,
)
from dex_examples.patterns.resource_control.request import Request
from dex_examples.shared.query import optional_query, required_query
def create_resource_control_blueprint(app_state: ExampleApp) -> Blueprint:
blueprint = Blueprint(
"resource_control", __name__, url_prefix="/patterns/resource-control"
)
@blueprint.get("/request")
async def enqueue_request() -> Response:
request = Request(required_query("id"), optional_query("data", "abcd"))
# A real deployment would rank instances by usage instead of picking one
# at random, then check availability before enqueueing.
instance_id = random.choice(SPOT_INSTANCE_IDS)
flow_id = f"controller_flow_{instance_id}"
try:
accepted = await app_state.client.invoke_rpc(
app_state.controller.enqueue,
flow_id,
request,
)
except FlowNotActiveOrNotFoundError:
await app_state.client.start_flow(
app_state.controller,
flow_id,
request,
start_options().with_attribute(
ControllerFlow.instance_id,
instance_id,
),
)
accepted = True
message = (
"request is accepted"
if accepted
else "request is denied because instance is busy. Please retry later"
)
return jsonify({"flowID": flow_id, "accepted": accepted, "message": message})
@blueprint.get("/shutdown")
async def shutdown() -> str:
instance_id = required_query("instance_id")
await app_state.client.invoke_rpc(
app_state.controller.shutdown,
f"controller_flow_{instance_id}",
)
return "done"
@blueprint.get("/processing/describe")
async def describe_processing() -> str:
return await app_state.client.invoke_rpc(
app_state.processing.describe,
f"processing-{required_query('id')}",
)
return blueprint