Skip to content

Commit 8681f7b

Browse files
Various router and auth fixes (#656)
Add data collection groups finding to session_control so it can be accessed by client Move the default destination determination to new file and require token in it to avoid defaulting to client token Adjust the model for failed posts to match the client Fix log on failed posts
1 parent 8c5718e commit 8681f7b

File tree

10 files changed

+127
-91
lines changed

10 files changed

+127
-91
lines changed

src/murfey/client/contexts/spa.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ def _position_analysis(
302302
data_collection_group = (
303303
capture_get(
304304
base_url=str(environment.url.geturl()),
305-
router_name="session_info.router",
305+
router_name="session_control.router",
306306
function_name="get_dc_groups",
307307
token=self._token,
308308
session_id=environment.murfey_session,

src/murfey/client/destinations.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
from __future__ import annotations
2+
3+
import logging
4+
from pathlib import Path
5+
from typing import Dict
6+
7+
from murfey.client.analyser import Analyser
8+
from murfey.client.instance_environment import (
9+
MurfeyInstanceEnvironment,
10+
global_env_lock,
11+
)
12+
from murfey.util.client import capture_get, capture_post
13+
14+
logger = logging.getLogger("murfey.client.destinations")
15+
16+
17+
def determine_default_destination(
18+
visit: str,
19+
source: Path,
20+
destination: str,
21+
environment: MurfeyInstanceEnvironment,
22+
analysers: Dict[Path, Analyser],
23+
token: str,
24+
touch: bool = False,
25+
extra_directory: str = "",
26+
include_mid_path: bool = True,
27+
use_suggested_path: bool = True,
28+
) -> str:
29+
machine_data = capture_get(
30+
base_url=str(environment.url.geturl()),
31+
router_name="session_control.router",
32+
function_name="machine_info_by_instrument",
33+
token=token,
34+
instrument_name=environment.instrument_name,
35+
).json()
36+
_default = ""
37+
if environment.processing_only_mode and environment.sources:
38+
logger.info(f"Processing only mode with sources {environment.sources}")
39+
_default = str(environment.sources[0].absolute()) or str(Path.cwd())
40+
elif machine_data.get("data_directories"):
41+
for data_dir in machine_data["data_directories"]:
42+
if source.absolute() == Path(data_dir).absolute():
43+
_default = f"{destination}/{visit}"
44+
break
45+
else:
46+
try:
47+
mid_path = source.absolute().relative_to(Path(data_dir).absolute())
48+
if use_suggested_path:
49+
with global_env_lock:
50+
source_name = (
51+
source.name
52+
if source.name != "Images-Disc1"
53+
else source.parent.name
54+
)
55+
if environment.destination_registry.get(source_name):
56+
_default = environment.destination_registry[source_name]
57+
else:
58+
suggested_path_response = capture_post(
59+
base_url=str(environment.url.geturl()),
60+
router_name="file_io_instrument.router",
61+
function_name="suggest_path",
62+
token=token,
63+
visit_name=visit,
64+
session_id=environment.murfey_session,
65+
data={
66+
"base_path": f"{destination}/{visit}/{mid_path.parent if include_mid_path else ''}/raw",
67+
"touch": touch,
68+
"extra_directory": extra_directory,
69+
},
70+
)
71+
if suggested_path_response is None:
72+
raise RuntimeError("Murfey server is unreachable")
73+
_default = suggested_path_response.json().get(
74+
"suggested_path"
75+
)
76+
environment.destination_registry[source_name] = _default
77+
else:
78+
_default = f"{destination}/{visit}/{mid_path if include_mid_path else source.name}"
79+
break
80+
except (ValueError, KeyError):
81+
_default = ""
82+
else:
83+
_default = ""
84+
else:
85+
_default = f"{destination}/{visit}"
86+
return (
87+
_default + f"/{extra_directory}"
88+
if not _default.endswith("/")
89+
else _default + f"{extra_directory}"
90+
)

src/murfey/client/multigrid_control.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@
1414
from murfey.client.analyser import Analyser
1515
from murfey.client.contexts.spa import SPAModularContext
1616
from murfey.client.contexts.tomo import TomographyContext
17+
from murfey.client.destinations import determine_default_destination
1718
from murfey.client.instance_environment import MurfeyInstanceEnvironment
1819
from murfey.client.rsync import RSyncer, RSyncerUpdate, TransferResult
19-
from murfey.client.tui.screens import determine_default_destination
2020
from murfey.client.watchdir import DirWatcher
2121
from murfey.util import posix_path
2222
from murfey.util.client import (
@@ -267,6 +267,7 @@ def _start_rsyncer_multigrid(
267267
self._environment.default_destinations[source],
268268
self._environment,
269269
self.analysers or {},
270+
self.token,
270271
touch=True,
271272
extra_directory=extra_directory,
272273
include_mid_path=include_mid_path,

src/murfey/client/tui/app.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from murfey.client.analyser import Analyser
1717
from murfey.client.contexts.spa import SPAModularContext
1818
from murfey.client.contexts.tomo import TomographyContext
19+
from murfey.client.destinations import determine_default_destination
1920
from murfey.client.instance_environment import MurfeyInstanceEnvironment
2021
from murfey.client.rsync import RSyncer, RSyncerUpdate, TransferResult
2122
from murfey.client.tui.screens import (
@@ -27,7 +28,6 @@
2728
VisitCreation,
2829
VisitSelection,
2930
WaitingScreen,
30-
determine_default_destination,
3131
)
3232
from murfey.client.tui.status_bar import StatusBar
3333
from murfey.client.watchdir import DirWatcher
@@ -177,6 +177,7 @@ def _start_rsyncer_multigrid(
177177
self._default_destinations[source],
178178
self._environment,
179179
self.analysers,
180+
token,
180181
touch=True,
181182
extra_directory=extra_directory,
182183
include_mid_path=include_mid_path,

src/murfey/client/tui/screens.py

Lines changed: 3 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,10 @@
4545
)
4646
from werkzeug.utils import secure_filename
4747

48-
from murfey.client.analyser import Analyser
4948
from murfey.client.contexts.spa import SPAModularContext
5049
from murfey.client.contexts.tomo import TomographyContext
50+
from murfey.client.destinations import determine_default_destination
5151
from murfey.client.gain_ref import determine_gain_ref
52-
from murfey.client.instance_environment import (
53-
MurfeyInstanceEnvironment,
54-
global_env_lock,
55-
)
5652
from murfey.client.rsync import RSyncer
5753
from murfey.util import posix_path
5854
from murfey.util.client import (
@@ -72,81 +68,6 @@
7268
instrument_name = read_config()["Murfey"].get("instrument_name", "")
7369

7470

75-
def determine_default_destination(
76-
visit: str,
77-
source: Path,
78-
destination: str,
79-
environment: MurfeyInstanceEnvironment,
80-
analysers: Dict[Path, Analyser],
81-
touch: bool = False,
82-
extra_directory: str = "",
83-
include_mid_path: bool = True,
84-
use_suggested_path: bool = True,
85-
) -> str:
86-
machine_data = capture_get(
87-
base_url=str(environment.url.geturl()),
88-
router_name="session_control.router",
89-
function_name="machine_info_by_instrument",
90-
token=token,
91-
instrument_name=environment.instrument_name,
92-
).json()
93-
_default = ""
94-
if environment.processing_only_mode and environment.sources:
95-
log.info(f"Processing only mode with sources {environment.sources}")
96-
_default = str(environment.sources[0].absolute()) or str(Path.cwd())
97-
elif machine_data.get("data_directories"):
98-
for data_dir in machine_data["data_directories"]:
99-
if source.absolute() == Path(data_dir).absolute():
100-
_default = f"{destination}/{visit}"
101-
break
102-
else:
103-
try:
104-
mid_path = source.absolute().relative_to(Path(data_dir).absolute())
105-
if use_suggested_path:
106-
with global_env_lock:
107-
source_name = (
108-
source.name
109-
if source.name != "Images-Disc1"
110-
else source.parent.name
111-
)
112-
if environment.destination_registry.get(source_name):
113-
_default = environment.destination_registry[source_name]
114-
else:
115-
suggested_path_response = capture_post(
116-
base_url=str(environment.url.geturl()),
117-
router_name="file_io_instrument.router",
118-
function_name="suggest_path",
119-
token=token,
120-
visit_name=visit,
121-
session_id=environment.murfey_session,
122-
data={
123-
"base_path": f"{destination}/{visit}/{mid_path.parent if include_mid_path else ''}/raw",
124-
"touch": touch,
125-
"extra_directory": extra_directory,
126-
},
127-
)
128-
if suggested_path_response is None:
129-
raise RuntimeError("Murfey server is unreachable")
130-
_default = suggested_path_response.json().get(
131-
"suggested_path"
132-
)
133-
environment.destination_registry[source_name] = _default
134-
else:
135-
_default = f"{destination}/{visit}/{mid_path if include_mid_path else source.name}"
136-
break
137-
except (ValueError, KeyError):
138-
_default = ""
139-
else:
140-
_default = ""
141-
else:
142-
_default = f"{destination}/{visit}"
143-
return (
144-
_default + f"/{extra_directory}"
145-
if not _default.endswith("/")
146-
else _default + f"{extra_directory}"
147-
)
148-
149-
15071
class InputResponse(NamedTuple):
15172
question: str
15273
allowed_responses: List[str] | None = None
@@ -349,6 +270,7 @@ def on_button_pressed(self, event: Button.Pressed) -> None:
349270
defd,
350271
self.app._environment,
351272
self.app.analysers,
273+
token,
352274
touch=True,
353275
)
354276
visit_path = defd + f"/{text}"
@@ -1077,6 +999,7 @@ def compose(self):
1077999
f"{datetime.now().year}",
10781000
self.app._environment,
10791001
self.app.analysers,
1002+
token,
10801003
touch=True,
10811004
)
10821005
if dest and dest in destinations:

src/murfey/server/api/session_control.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,16 @@ def remove_session(session_id: MurfeySessionID, db=murfey_db):
165165
remove_session_by_id(session_id, db)
166166

167167

168+
@router.get("/sessions/{session_id}/data_collection_groups")
169+
def get_dc_groups(
170+
session_id: MurfeySessionID, db=murfey_db
171+
) -> Dict[str, DataCollectionGroup]:
172+
data_collection_groups = db.exec(
173+
select(DataCollectionGroup).where(DataCollectionGroup.session_id == session_id)
174+
).all()
175+
return {dcg.tag: dcg for dcg in data_collection_groups}
176+
177+
168178
@router.post("/sessions/{session_id}/successful_processing")
169179
def register_processing_success_in_ispyb(
170180
session_id: MurfeySessionID, db=ispyb_db, murfey_db=murfey_db
@@ -196,16 +206,20 @@ def count_number_of_movies(db=murfey_db) -> Dict[str, int]:
196206

197207

198208
class PostInfo(BaseModel):
199-
url: str
209+
router_name: str
210+
function_name: str
200211
data: dict
212+
kwargs: dict
201213

202214

203215
@router.post("/instruments/{instrument_name}/failed_client_post")
204216
def failed_client_post(instrument_name: str, post_info: PostInfo):
205217
zocalo_message = {
206218
"register": "failed_client_post",
207-
"url": post_info.url,
208-
"json": post_info.data,
219+
"router_name": post_info.router_name,
220+
"function_name": post_info.function_name,
221+
"data": post_info.data,
222+
"kwargs": post_info.kwargs,
209223
}
210224
if _transport_object:
211225
_transport_object.send(_transport_object.feedback_queue, zocalo_message)

src/murfey/server/api/session_info.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ class VisitEndTime(BaseModel):
162162
end_time: Optional[datetime] = None
163163

164164

165-
@router.post("/instruments/{instrument_name}/visits/{visit}/session/{name}")
165+
@router.post("/instruments/{instrument_name}/visits/{visit}/sessions/{name}")
166166
def create_session(
167167
instrument_name: MurfeyInstrumentName,
168168
visit: str,

src/murfey/server/demo_api.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ class SessionClients(BaseModel):
228228
clients: List[ClientEnvironment]
229229

230230

231-
@router.get("/session/{session_id}")
231+
@router.get("/sessions/{session_id}")
232232
async def get_session(session_id: MurfeySessionID, db=murfey_db) -> SessionClients:
233233
session = db.exec(select(Session).where(Session.id == session_id)).one()
234234
clients = db.exec(
@@ -996,7 +996,7 @@ async def get_tiff(visit_name: str, session_id: int, tiff_path: str, db=murfey_d
996996
return FileResponse(path=test_path)
997997

998998

999-
@router.post("/instruments/{instrument_name}/visits/{visit}/session/{name}")
999+
@router.post("/instruments/{instrument_name}/visits/{visit}/sessions/{name}")
10001000
def create_session(instrument_name: str, visit: str, name: str, db=murfey_db) -> int:
10011001
s = Session(name=name, visit=visit, instrument_name=instrument_name)
10021002
db.add(s)

src/murfey/util/client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def capture_post(
8585
response = requests.Response()
8686
if response.status_code != 200:
8787
logger.warning(
88-
f"Response to post to {url} with data {json} had status code "
88+
f"Response to post to {url} with data {data} had status code "
8989
f"{response.status_code}. The reason given was {response.reason}"
9090
)
9191
client_config = read_config()

src/murfey/util/route_manifest.yaml

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -826,6 +826,13 @@ murfey.server.api.session_control.router:
826826
type: int
827827
methods:
828828
- DELETE
829+
- path: /session_info/sessions/{session_id}/data_collection_groups
830+
function: get_dc_groups
831+
path_params:
832+
- name: session_id
833+
type: int
834+
methods:
835+
- GET
829836
- path: /session_control/sessions/{session_id}/successful_processing
830837
function: register_processing_success_in_ispyb
831838
path_params:
@@ -1040,7 +1047,7 @@ murfey.server.api.session_info.router:
10401047
path_params: []
10411048
methods:
10421049
- GET
1043-
- path: /session_info/instruments/{instrument_name}/visits/{visit}/session/{name}
1050+
- path: /session_info/instruments/{instrument_name}/visits/{visit}/sessions/{name}
10441051
function: create_session
10451052
path_params:
10461053
- name: visit

0 commit comments

Comments
 (0)