haps-invocation 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ from .invocation import (
2
+ build_json_metadata,
3
+ create_api,
4
+ get_microservice,
5
+ create_cwl_task_state_file,
6
+ download_ebouts,
7
+ get_cwl_task_action,
8
+ initialize_cwl_task_state,
9
+ load_cwl_task_state,
10
+ recover_cwl_job,
11
+ recover_cwl_job_by_tag,
12
+ save_cwl_submitted_job_state,
13
+ run_haps,
14
+ wait_for_cwl_job,
15
+ mark_cwl_outputs_ready,
16
+ mark_cwl_task_expired,
17
+ create_scheduler_client,
18
+ wait_for_scheduler_job,
19
+ )
@@ -0,0 +1,1046 @@
1
+ from email.mime import application
2
+ import json
3
+ import os
4
+ from sched import scheduler
5
+ import shutil
6
+ import sys
7
+ import uuid
8
+
9
+ from pathlib import Path
10
+ from tempfile import TemporaryDirectory
11
+ from time import sleep
12
+ import time
13
+
14
+ from haps_client import HapsClient
15
+ from haps_plugin_scheduler_client import PLUGIN_TAG, SchedulerClient
16
+
17
+
18
+ try: # optional: load credentials from a .env file
19
+ from dotenv import load_dotenv
20
+ except ImportError: # python-dotenv not installed
21
+ load_dotenv = None
22
+
23
+
24
+ def _load_credentials():
25
+ """Return (username, password) for eBservice.
26
+
27
+ Values come from the environment. If python-dotenv is installed, a .env
28
+ file is loaded first: the path in EXA_ATOW_ENV_FILE when set, otherwise
29
+ the nearest .env found from the working directory. Existing environment
30
+ variables always win.
31
+ """
32
+ if load_dotenv is not None:
33
+ env_file = os.environ.get("EXA_ATOW_ENV_FILE")
34
+ if env_file:
35
+ load_dotenv(env_file, override=False)
36
+ else:
37
+ load_dotenv(override=False)
38
+
39
+ missing = [
40
+ name
41
+ for name in ("EXA_ATOW_USERNAME", "EXA_ATOW_PASSWORD")
42
+ if not os.environ.get(name)
43
+ ]
44
+ if missing:
45
+ raise RuntimeError(
46
+ "Missing eBservice credentials: "
47
+ + ", ".join(missing)
48
+ + ". Export them, or point EXA_ATOW_ENV_FILE at a .env file "
49
+ "containing them (requires python-dotenv)."
50
+ )
51
+
52
+ return os.environ["EXA_ATOW_USERNAME"], os.environ["EXA_ATOW_PASSWORD"]
53
+
54
+
55
+ EBUFFER_BASE_URL = "https://ebuffer.aqmo.org/"
56
+ EBSERVICE_BASE_URL = "https://ebservice.aqmo.org/"
57
+
58
+
59
+ def _log(message: str):
60
+ """
61
+ Write runtime logs to stderr.
62
+
63
+ This is required for MCP stdio servers because stdout is
64
+ reserved for MCP protocol messages. It is also safe for
65
+ generated CWL/Galaxy proxy tasks.
66
+ """
67
+ print(
68
+ message,
69
+ file=sys.stderr,
70
+ flush=True,
71
+ )
72
+
73
+
74
+ # ----------------------------------------------------------------------
75
+ # eBservice client
76
+ # ----------------------------------------------------------------------
77
+
78
+ def create_api(
79
+ username: str,
80
+ password: str,
81
+ ):
82
+ return HapsClient(
83
+ username=username,
84
+ password=password,
85
+ ebservice_url=EBSERVICE_BASE_URL,
86
+ ebuffer_url=EBUFFER_BASE_URL,
87
+ )
88
+
89
+
90
+ # ----------------------------------------------------------------------
91
+ # Microservice
92
+ # ----------------------------------------------------------------------
93
+
94
+ def get_microservice(
95
+ api,
96
+ application: dict,
97
+ ):
98
+ services = api.mservices.search(tags=[PLUGIN_TAG], match_all=True)
99
+
100
+ for service in services:
101
+ if (
102
+ service.name == application["name"]
103
+ and service.mime_type == application["mime_type"]
104
+ ):
105
+ return service
106
+
107
+ raise ValueError(
108
+ f"Application '{application['name']}' "
109
+ f"with MIME type '{application['mime_type']}' was not found."
110
+ )
111
+
112
+ # ----------------------------------------------------------------------
113
+ # Create scheduler client
114
+ # ----------------------------------------------------------------------
115
+
116
+ def create_scheduler_client(
117
+ api,
118
+ service,
119
+ ):
120
+ return SchedulerClient(
121
+ api,
122
+ service.uuid,
123
+ )
124
+
125
+
126
+ def wait_for_scheduler_job(
127
+ scheduler,
128
+ task_name: str,
129
+ ):
130
+ scheduler.monitor()
131
+ scheduler.refresh()
132
+
133
+ status = scheduler.haps_status
134
+
135
+ if status is None:
136
+ raise RuntimeError(
137
+ f"HAPS '{task_name}' has no execution status."
138
+ )
139
+
140
+ status = status.value.lower()
141
+
142
+ _log(
143
+ f"HAPS '{task_name}' finished "
144
+ f"with status: {status}"
145
+ )
146
+
147
+ if status != "completed":
148
+ raise RuntimeError(
149
+ f"HAPS '{task_name}' ended with "
150
+ f"status '{status}'."
151
+ )
152
+
153
+ return status
154
+
155
+ # ----------------------------------------------------------------------
156
+ # CWL workflow-instance recovery
157
+ # ----------------------------------------------------------------------
158
+
159
+ def get_cwl_instance_directory() -> Path:
160
+ """
161
+ Return the persistent directory of the current CWL workflow instance.
162
+ """
163
+
164
+ # Read the workflow instance identifier.
165
+ instance_id = os.environ.get(
166
+ "EXA_ATOW_INSTANCE_ID"
167
+ )
168
+
169
+ if not instance_id:
170
+ raise RuntimeError(
171
+ "EXA_ATOW_INSTANCE_ID is not set."
172
+ )
173
+
174
+ # Read the persistent Exa-AToW state directory.
175
+ state_root = os.environ.get(
176
+ "EXA_ATOW_STATE_DIR"
177
+ )
178
+
179
+ if not state_root:
180
+ raise RuntimeError(
181
+ "EXA_ATOW_STATE_DIR is not set."
182
+ )
183
+
184
+ # Store all task states of this workflow execution
185
+ # inside the same persistent instance directory.
186
+ instance_directory = (
187
+ Path(state_root)
188
+ / "instances"
189
+ / instance_id
190
+ )
191
+
192
+ # Create the directory when starting a new instance.
193
+ # For recovery, the existing directory is reused.
194
+ instance_directory.mkdir(
195
+ parents=True,
196
+ exist_ok=True,
197
+ )
198
+
199
+ return instance_directory
200
+
201
+
202
+ def create_cwl_task_state_file(
203
+ task_id: str,
204
+ ) -> Path:
205
+ """
206
+ Return the state-file path for one task in the current CWL instance.
207
+ """
208
+
209
+ instance_directory = get_cwl_instance_directory()
210
+
211
+ # Each task keeps its own state file inside the workflow instance.
212
+ return instance_directory / f"{task_id}.json"
213
+
214
+
215
+ def initialize_cwl_task_state(
216
+ state_file: Path,
217
+ task_id: str,
218
+ hpc_center: str,
219
+ service,
220
+ ) -> dict:
221
+ """
222
+ Create a fresh persistent state for one CWL task submission.
223
+ """
224
+
225
+ # Get the workflow instance to which this task belongs.
226
+ instance_id = os.environ["EXA_ATOW_INSTANCE_ID"]
227
+
228
+ # Create a unique identifier for this submission attempt.
229
+ # A resubmitted task must not reuse the recovery tag
230
+ # of its previous remote job.
231
+ attempt_id = uuid.uuid4().hex[:8]
232
+
233
+ # Build a recovery tag that uniquely identifies
234
+ # this workflow instance, task, and submission attempt.
235
+ recovery_tag = (
236
+ f"exa-atow::{instance_id}::"
237
+ f"{task_id}::{attempt_id}"
238
+ )
239
+
240
+ # Create the initial state before submitting the remote job.
241
+ state_data = {
242
+ "instance_id": instance_id,
243
+ "task_id": task_id,
244
+ "hpc_center": hpc_center,
245
+ "microservice_uuid": service.uuid,
246
+ "attempt_id": attempt_id,
247
+ "job_uuid": None,
248
+ "status": "submitting",
249
+ "outputs_ready": False,
250
+ "recovery_tag": recovery_tag,
251
+ }
252
+
253
+ # Persist the state so it survives a proxy interruption.
254
+ _write_state_file(
255
+ state_file=state_file,
256
+ state_data=state_data,
257
+ )
258
+
259
+ return state_data
260
+
261
+ def get_cwl_haps_status(job, scheduler=None) -> str:
262
+ """
263
+ Get the HAPS execution status for both
264
+ scheduler-based and direct HAPS jobs.
265
+ """
266
+
267
+ if scheduler is not None:
268
+ # Scheduler-based HAPS
269
+ scheduler.refresh()
270
+ status = scheduler.haps_status
271
+
272
+ else:
273
+ # Direct HAPS
274
+ status = job.get_run_status()
275
+
276
+ if status is None:
277
+ raise RuntimeError(
278
+ "HAPS job has no execution status."
279
+ )
280
+
281
+ # Support both enum values and strings.
282
+ return str(
283
+ getattr(status, "name", status)
284
+ ).lower()
285
+
286
+
287
+ def save_cwl_submitted_job_state(
288
+ state_file: Path,
289
+ state_data: dict,
290
+ scheduler,
291
+ job,
292
+ ebout_buffers: dict | None = None,
293
+ ) -> dict:
294
+ """
295
+ Save the remote job UUID and current status
296
+ for both scheduler-based and direct HAPS.
297
+ """
298
+
299
+ status = get_cwl_haps_status(
300
+ job=job,
301
+ scheduler=scheduler,
302
+ )
303
+
304
+ # Update the existing task state.
305
+ state_data["job_uuid"] = job.uuid
306
+ state_data["status"] = status
307
+
308
+ # Save eBout UUIDs for CWL job recovery.
309
+ if ebout_buffers is not None:
310
+ state_data["ebout_uuids"] = {
311
+ name: str(buffer.uuid)
312
+ for name, buffer in ebout_buffers.items()
313
+ }
314
+
315
+ # Persist the updated state.
316
+ _write_state_file(
317
+ state_file=state_file,
318
+ state_data=state_data,
319
+ )
320
+
321
+ return state_data
322
+
323
+
324
+
325
+ def wait_for_cwl_job(
326
+ scheduler,
327
+ task_id: str,
328
+ state_file: Path,
329
+ state_data: dict,
330
+ job=None,
331
+ ) -> str:
332
+ """
333
+ Monitor both scheduler-based and direct HAPS jobs
334
+ while persisting CWL task status.
335
+ """
336
+
337
+ terminal_statuses = {
338
+ "completed",
339
+ "failed",
340
+ "cancelled",
341
+ "stopped",
342
+ "suspended",
343
+ "error",
344
+ }
345
+
346
+ # Use the scheduler's job if no explicit job is provided.
347
+ if job is None:
348
+ if scheduler is None:
349
+ raise ValueError("No HAPS job provided.")
350
+ job = scheduler.job
351
+
352
+ last_logged_status = None
353
+
354
+ while True:
355
+ status = get_cwl_haps_status(
356
+ job=job,
357
+ scheduler=scheduler,
358
+ )
359
+
360
+ # Log status changes.
361
+ if status != last_logged_status:
362
+ print(
363
+ f"{task_id}: status = {status}",
364
+ flush=True,
365
+ )
366
+ last_logged_status = status
367
+
368
+ # Persist status changes.
369
+ if state_data.get("status") != status:
370
+ state_data["status"] = status
371
+
372
+ _write_state_file(
373
+ state_file=state_file,
374
+ state_data=state_data,
375
+ )
376
+
377
+ if status in terminal_statuses:
378
+ return status
379
+
380
+ time.sleep(10)
381
+
382
+
383
+ def load_cwl_task_state(
384
+ state_file: Path,
385
+ ) -> dict | None:
386
+ """
387
+ Load the saved state of a CWL task if it already exists.
388
+ """
389
+
390
+ # If there is no state file, this task has not been executed yet.
391
+ if not state_file.is_file():
392
+ return None
393
+
394
+ # Read and return the previously saved task state.
395
+ return json.loads(
396
+ state_file.read_text(
397
+ encoding="utf-8"
398
+ )
399
+ )
400
+
401
+
402
+
403
+ def recover_cwl_job(
404
+ api,
405
+ state_data: dict,
406
+ execution_backend: str = "scheduler",
407
+ service=None,
408
+ ):
409
+ """
410
+ Recover a scheduler-based or direct HAPS job by UUID.
411
+ """
412
+
413
+ job_uuid = state_data.get("job_uuid")
414
+
415
+ if not job_uuid:
416
+ return None
417
+
418
+ if execution_backend == "scheduler":
419
+ scheduler = SchedulerClient.attach(
420
+ api,
421
+ job_uuid,
422
+ )
423
+
424
+ _log(f"Recovered CWL scheduler job: {scheduler.job.uuid}")
425
+ return scheduler
426
+
427
+ if execution_backend == "direct":
428
+ if service is None:
429
+ raise ValueError(
430
+ "Direct HAPS recovery requires a microservice."
431
+ )
432
+
433
+ job = service.get_job(job_uuid)
434
+
435
+ _log(f"Recovered CWL direct HAPS job: {job.uuid}")
436
+ return job
437
+
438
+ raise ValueError(
439
+ f"Unsupported execution backend: {execution_backend}"
440
+ )
441
+
442
+
443
+
444
+
445
+ def recover_cwl_job_by_tag(
446
+ api,
447
+ recovery_tag: str,
448
+ execution_backend: str = "scheduler",
449
+ service=None,
450
+ ):
451
+ """
452
+ Recover a scheduler-based or direct HAPS job
453
+ using its recovery tag.
454
+ """
455
+
456
+ if execution_backend == "scheduler":
457
+ matching_jobs = [
458
+ existing_job
459
+ for existing_job in SchedulerClient.list(api)
460
+ if recovery_tag in (existing_job.tags or [])
461
+ ]
462
+
463
+ elif execution_backend == "direct":
464
+ if service is None:
465
+ raise ValueError(
466
+ "Direct HAPS recovery requires a microservice."
467
+ )
468
+
469
+ # Retrieve all matching jobs, page by page.
470
+ matching_jobs = []
471
+ page_size = 100
472
+ offset = 0
473
+
474
+ while True:
475
+ jobs = service.list_jobs(
476
+ tags=[recovery_tag],
477
+ match_all=True,
478
+ limit=page_size,
479
+ skip=offset,
480
+ )
481
+
482
+ matching_jobs.extend(jobs)
483
+
484
+ if len(jobs) < page_size:
485
+ break
486
+
487
+ offset += page_size
488
+
489
+ else:
490
+ raise ValueError(
491
+ f"Unsupported execution backend: {execution_backend}"
492
+ )
493
+
494
+ if not matching_jobs:
495
+ return None
496
+
497
+ if len(matching_jobs) > 1:
498
+ raise RuntimeError(
499
+ f"Multiple jobs found with recovery tag "
500
+ f"'{recovery_tag}'."
501
+ )
502
+
503
+ if execution_backend == "scheduler":
504
+ scheduler = SchedulerClient.attach(
505
+ api,
506
+ matching_jobs[0].uuid,
507
+ )
508
+
509
+ _log(
510
+ f"Recovered CWL scheduler job: "
511
+ f"{scheduler.job.uuid}"
512
+ )
513
+
514
+ return scheduler
515
+
516
+ # Direct HAPS recovery
517
+ job = service.get_job(matching_jobs[0].uuid)
518
+
519
+ _log(
520
+ f"Recovered CWL direct HAPS job: {job.uuid}"
521
+ )
522
+
523
+ return job
524
+
525
+
526
+
527
+ def get_cwl_task_action(
528
+ state_data: dict | None,
529
+ ) -> str:
530
+ """
531
+ Decide what the CWL proxy should do based on the saved task state.
532
+ """
533
+
534
+ # No saved state means the task has never been submitted.
535
+ if state_data is None:
536
+ return "submit"
537
+
538
+ status = state_data.get("status")
539
+
540
+ # The remote computation already completed.
541
+ # Recover the completed job so the proxy can recreate
542
+ # the outputs required by the new cwltool execution.
543
+ if status == "completed":
544
+ return "recover"
545
+
546
+ # The remote job already exists and may still be active.
547
+ if status in {
548
+ "initialized",
549
+ "submitting",
550
+ "pending",
551
+ "processing",
552
+ "suspended",
553
+ }:
554
+ return "recover"
555
+
556
+ # These states cannot be successfully reused, so the task
557
+ # needs a fresh remote submission.
558
+ if status in {
559
+ "failed",
560
+ "cancelled",
561
+ "stopped",
562
+ "expired",
563
+ }:
564
+ return "resubmit"
565
+
566
+ # Do not silently submit a new computation for an unknown state.
567
+ raise RuntimeError(
568
+ f"Unknown CWL task status: {status}"
569
+ )
570
+ def mark_cwl_task_expired(
571
+ state_file: Path,
572
+ state_data: dict,
573
+ ) -> dict:
574
+ """
575
+ Mark a CWL task as expired when its remote output buffers no longer exist.
576
+ """
577
+
578
+ # Record that the previous completed job can no longer
579
+ # provide its outputs.
580
+ state_data["status"] = "expired"
581
+ state_data["outputs_ready"] = False
582
+
583
+ # Persist the updated state.
584
+ _write_state_file(
585
+ state_file=state_file,
586
+ state_data=state_data,
587
+ )
588
+
589
+ return state_data
590
+
591
+
592
+ def mark_cwl_outputs_ready(
593
+ state_file: Path,
594
+ state_data: dict,
595
+ ) -> dict:
596
+ """
597
+ Mark the outputs of a completed CWL task as successfully processed.
598
+ """
599
+
600
+ # Record that the proxy successfully finished creating its outputs.
601
+ state_data["outputs_ready"] = True
602
+
603
+ # Persist the updated task state.
604
+ _write_state_file(
605
+ state_file=state_file,
606
+ state_data=state_data,
607
+ )
608
+
609
+ return state_data
610
+
611
+
612
+ # ----------------------------------------------------------------------
613
+ # Persistent recovery-state helpers
614
+ # ----------------------------------------------------------------------
615
+
616
+ def _write_state_file(
617
+ state_file: Path,
618
+ state_data: dict,
619
+ ):
620
+ """
621
+ Write a state file atomically.
622
+ """
623
+
624
+ state_file.parent.mkdir(
625
+ parents=True,
626
+ exist_ok=True,
627
+ )
628
+
629
+ temporary_state_file = (
630
+ state_file.with_suffix(".tmp")
631
+ )
632
+
633
+ temporary_state_file.write_text(
634
+ json.dumps(
635
+ state_data,
636
+ indent=2,
637
+ ),
638
+ encoding="utf-8",
639
+ )
640
+
641
+ temporary_state_file.replace(
642
+ state_file
643
+ )
644
+
645
+
646
+ # ----------------------------------------------------------------------
647
+ # Run HAPS for MCP
648
+ # ----------------------------------------------------------------------
649
+
650
+ def run_haps(
651
+ task_name: str,
652
+ application: dict,
653
+ input_files: list[str],
654
+ job_arguments: list[str],
655
+ hpc_center: str,
656
+ ebin_inputs: list[dict] | None = None,
657
+ return_ebout_uuids: bool = False,
658
+ ):
659
+ """
660
+ Execute one HAPS request for an MCP tool.
661
+ """
662
+ username, password = _load_credentials()
663
+
664
+ api = create_api(
665
+ username=username,
666
+ password=password,
667
+ )
668
+
669
+
670
+ use_scheduler = (
671
+ "plugin::scheduler" in application.get("tags", [])
672
+ )
673
+
674
+ if use_scheduler:
675
+ # Scheduler-based HAPS
676
+ service = get_microservice(
677
+ api=api,
678
+ application=application,
679
+ )
680
+
681
+ else:
682
+ # Direct HAPS
683
+ services = api.mservices.search(
684
+ tags=application.get("tags", []),
685
+ match_all=True,
686
+ )
687
+
688
+ service = next(
689
+ (
690
+ s for s in services
691
+ if s.name == application["name"]
692
+ and s.mime_type == application["mime_type"]
693
+ ),
694
+ None,
695
+ )
696
+
697
+ if service is None:
698
+ raise RuntimeError(
699
+ f"HAPS '{application['name']}' not found"
700
+ )
701
+
702
+
703
+ ebout_buffers = {}
704
+
705
+ ebin = []
706
+
707
+
708
+ # ----------------------------------------------------------
709
+ # Prepare eBins: upload files or reuse existing buffers.
710
+ # ----------------------------------------------------------
711
+
712
+ if ebin_inputs is None:
713
+ ebin_inputs = [
714
+ {"kind": "file", "value": path}
715
+ for path in input_files
716
+ ]
717
+
718
+ for ebin_input in ebin_inputs:
719
+ kind = ebin_input["kind"]
720
+ value = ebin_input["value"]
721
+
722
+ if kind == "uuid":
723
+ # Reuse an existing eBuffer.
724
+ ebin.append(str(value))
725
+
726
+ elif kind == "file":
727
+ # Upload a local file to a new eBuffer.
728
+ input_path = Path(value)
729
+
730
+ if not input_path.is_file():
731
+ raise FileNotFoundError(input_path)
732
+
733
+ input_buffer = api.buffers.create(
734
+ lifespan=3600,
735
+ reserved_size=max(1, input_path.stat().st_size),
736
+ tags=application.get("tags", []),
737
+ )
738
+
739
+ input_buffer.fill(input_path.read_bytes())
740
+ ebin.append(input_buffer.uuid)
741
+
742
+ else:
743
+ raise ValueError(
744
+ f"Unsupported eBin input kind: {kind}"
745
+ )
746
+
747
+ # ----------------------------------------------------------
748
+ # Create eBouts
749
+ # ----------------------------------------------------------
750
+
751
+ ebout = []
752
+
753
+ for ebout_name in application[
754
+ "ebout_names"
755
+ ]:
756
+ output_buffer = api.buffers.create(
757
+ lifespan=3600,
758
+ reserved_size=10_000_000,
759
+ tags=application.get(
760
+ "tags",
761
+ [],
762
+ ),
763
+ )
764
+
765
+ ebout_buffers[
766
+ ebout_name
767
+ ] = output_buffer
768
+
769
+ ebout.append(
770
+ output_buffer.uuid
771
+ )
772
+
773
+ # ----------------------------------------------------------
774
+ # Submit job
775
+ # ----------------------------------------------------------
776
+
777
+ job_data = {
778
+ "arguments": job_arguments,
779
+ "ebin": ebin,
780
+ "ebout": ebout,
781
+ "tags": (
782
+ application.get(
783
+ "tags",
784
+ [],
785
+ )
786
+ + [
787
+ f"hpc::{hpc_center}",
788
+ ]
789
+ ),
790
+ }
791
+
792
+ _log(
793
+ f"Submitting the "
794
+ f"{task_name} job"
795
+ )
796
+
797
+
798
+ if use_scheduler:
799
+ # HAPS using the scheduler plugin
800
+ scheduler = create_scheduler_client(
801
+ api=api,
802
+ service=service,
803
+ )
804
+
805
+ scheduler.submit_job(
806
+ job_data["arguments"],
807
+ ebin=job_data["ebin"],
808
+ ebout=job_data["ebout"],
809
+ tags=job_data["tags"],
810
+ )
811
+
812
+ job = scheduler.job
813
+
814
+ else:
815
+ # Direct HAPS without scheduler plugin
816
+ scheduler = None
817
+ job = service.submit_job(job_data)
818
+
819
+
820
+ _log(
821
+ f"Submitted job UUID: "
822
+ f"{job.uuid}"
823
+ )
824
+
825
+ # --------------------------------------------------------------
826
+ # Wait
827
+ # --------------------------------------------------------------
828
+
829
+
830
+ if use_scheduler:
831
+ # Scheduler-based HAPS
832
+ status = wait_for_scheduler_job(
833
+ scheduler=scheduler,
834
+ task_name=task_name,
835
+ )
836
+
837
+ scheduler.refresh()
838
+
839
+ else:
840
+ # Direct HAPS
841
+ terminal_statuses = {
842
+ "completed",
843
+ "failed",
844
+ "cancelled",
845
+ "stopped",
846
+ "suspended",
847
+ "error",
848
+ }
849
+
850
+ deadline = time.monotonic() + 3600
851
+
852
+ while True:
853
+ reported_status = job.get_run_status()
854
+ status = str(
855
+ getattr(reported_status, "value", reported_status)
856
+ ).lower()
857
+
858
+ _log(f"{task_name}: status = {status}")
859
+
860
+ if status in terminal_statuses:
861
+ break
862
+
863
+ if time.monotonic() >= deadline:
864
+ raise TimeoutError(
865
+ f"HAPS '{task_name}' monitoring timed out."
866
+ )
867
+
868
+ time.sleep(2)
869
+
870
+ if status != "completed":
871
+ raise RuntimeError(
872
+ f"HAPS '{task_name}' failed with status '{status}'."
873
+ )
874
+
875
+ job.refresh()
876
+
877
+
878
+ if return_ebout_uuids:
879
+ ebout_uuids = {
880
+ name: str(buffer.uuid)
881
+ for name, buffer in ebout_buffers.items()
882
+ }
883
+
884
+ return (
885
+ scheduler,
886
+ job,
887
+ status,
888
+ ebout_uuids,
889
+ )
890
+
891
+ return (
892
+ scheduler,
893
+ job,
894
+ status,
895
+ )
896
+
897
+
898
+ # ----------------------------------------------------------------------
899
+ # JSON metadata outputs
900
+ # ----------------------------------------------------------------------
901
+
902
+ def build_json_metadata(
903
+ haps_description: dict,
904
+ output_name: str,
905
+ job,
906
+ status: str,
907
+ hpc_center: str,
908
+ ebout_uuids: dict | None = None,
909
+ ) -> dict:
910
+ application = haps_description[
911
+ "application"
912
+ ]
913
+
914
+ job.refresh()
915
+
916
+ result_values = (
917
+ job.results or []
918
+ )
919
+ metadata = {}
920
+
921
+ for mapping in haps_description[
922
+ "output_mappings"
923
+ ]:
924
+ if (
925
+ mapping["tool_output"]
926
+ != output_name
927
+ ):
928
+ continue
929
+
930
+ source_type = mapping[
931
+ "source_type"
932
+ ]
933
+
934
+ source_name = mapping[
935
+ "source_name"
936
+ ]
937
+
938
+ field = mapping["field"]
939
+
940
+ if source_type == "result":
941
+ result_index = application[
942
+ "result_names"
943
+ ].index(
944
+ source_name
945
+ )
946
+
947
+ if (
948
+ len(result_values)
949
+ <= result_index
950
+ ):
951
+ raise RuntimeError(
952
+ f"Job result "
953
+ f"'{source_name}' is missing"
954
+ )
955
+
956
+ value = result_values[
957
+ result_index
958
+ ]
959
+
960
+ if isinstance(value, bytes):
961
+ value = value.decode(
962
+ "utf-8"
963
+ )
964
+
965
+ metadata[field] = value
966
+ elif source_type == "ebout_uuid":
967
+ if (
968
+ ebout_uuids is None
969
+ or source_name not in ebout_uuids
970
+ ):
971
+ raise RuntimeError(
972
+ f"eBout UUID for '{source_name}' is missing"
973
+ )
974
+
975
+ metadata[field] = str(
976
+ ebout_uuids[source_name]
977
+ )
978
+ elif source_type == "job" and source_name == "status":
979
+ metadata[field] = status
980
+
981
+ elif source_type == "control" and source_name == "hpc_center":
982
+ metadata[field] = hpc_center
983
+
984
+ else:
985
+ raise RuntimeError(
986
+ f"Unsupported MCP output mapping '{source_type}:{source_name}' "
987
+ f"for output '{output_name}', field '{field}'"
988
+ )
989
+
990
+ return metadata
991
+
992
+
993
+ # ----------------------------------------------------------------------
994
+ # eBout file output
995
+ # ----------------------------------------------------------------------
996
+
997
+
998
+ def download_ebouts(
999
+ scheduler,
1000
+ outputs: dict[str, Path],
1001
+ job=None,
1002
+ ) -> dict[str, Path]:
1003
+ """
1004
+ Download eBout files for scheduler-based
1005
+ and direct HAPS jobs.
1006
+ """
1007
+
1008
+ if scheduler is not None:
1009
+ # Scheduler-based HAPS
1010
+ downloader = scheduler
1011
+ elif job is not None:
1012
+ # Direct HAPS
1013
+ downloader = job
1014
+ else:
1015
+ raise ValueError(
1016
+ "Either scheduler or job must be provided."
1017
+ )
1018
+
1019
+ downloaded_outputs = {}
1020
+
1021
+ with TemporaryDirectory() as temporary_directory:
1022
+
1023
+ downloader.download_data(temporary_directory)
1024
+
1025
+ temporary_directory = Path(temporary_directory)
1026
+
1027
+ for ebout_name, output_path in outputs.items():
1028
+ source_file = temporary_directory / ebout_name
1029
+
1030
+ if not source_file.is_file():
1031
+ raise FileNotFoundError(
1032
+ f"Missing eBout file: {source_file}"
1033
+ )
1034
+
1035
+ output_path.parent.mkdir(
1036
+ parents=True,
1037
+ exist_ok=True,
1038
+ )
1039
+
1040
+ shutil.copy2(source_file, output_path)
1041
+
1042
+ downloaded_outputs[ebout_name] = (
1043
+ output_path.resolve()
1044
+ )
1045
+
1046
+ return downloaded_outputs
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: haps-invocation
3
+ Version: 0.2.1
4
+ Summary: Library for HAPS service invocation and data exchange
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: haps-client<0.6,>=0.5.0
10
+ Requires-Dist: haps-plugin-scheduler-client<0.6,>=0.5.0
11
+ Provides-Extra: dotenv
12
+ Requires-Dist: python-dotenv>=1.0; extra == "dotenv"
13
+ Dynamic: license-file
14
+
15
+ # haps-invocation
16
+
17
+ Runtime support for proxies generated by the xgtd-compiler Compiler.
18
+
19
+ ## Overview
20
+
21
+ haps-invocation provides the shared execution logic used by generated Galaxy tools, CWL tasks, and MCP servers to invoke HAPS applications.
22
+
23
+ The runtime is separated from the compiler because they are used at different stages:
24
+
25
+ - `xgtd-compiler` generates executable workflow and tool descriptions.
26
+ - `haps-invocation` supports the generated proxies while they are running.
27
+
28
+ This separation allows execution environments, such as Galaxy servers, to install the lightweight runtime without installing all compiler dependencies.
29
+
30
+ ## Features
31
+
32
+ The runtime supports:
33
+
34
+ - Submission of HAPS jobs through `HapsClient`
35
+ - Monitoring of submitted jobs
36
+ - Recovery of previously submitted jobs
37
+ - Persistent job-state management
38
+ - Processing of HAPS results
39
+ - Downloading eBout outputs
40
+ - Generation of JSON metadata for downstream workflow tasks
41
+
42
+ ## Installation
43
+
44
+ The recommended installation method is to install the complete Exa-AToW compiler:
45
+
46
+ ```bash
47
+ python -m pip install xgtd-compiler
48
+ ```
49
+
50
+ A compatible version of `haps-invocation` is installed automatically.
51
+
52
+ Execution environments that only run generated proxies can install the runtime directly:
53
+
54
+ ```bash
55
+ python -m pip install haps-invocation
56
+ ```
57
+
58
+ ## Requirements
59
+
60
+ - Python 3.11 or newer
61
+ - Access to a configured HAPS service
62
+ - Credentials and HPC-centre information required by the generated proxy
63
+
64
+ The runtime installs `haps-client` and `haps-plugin-scheduler-client` as dependencies.
65
+
66
+ ## Usage
67
+
68
+ The runtime is normally not invoked directly from the command line. It is imported by the Python proxies generated by the Exa-AToW compiler.
69
+
70
+ For example, generated proxies import runtime functionality using:
71
+
72
+ ```python
73
+ from haps_invocation import run_haps
74
+ ```
75
+
76
+ Depending on the compilation mode, generated code may also use runtime functions for recovery, metadata generation, output downloading, and job-state management.
77
+
78
+ ## Compilation and execution model
79
+
80
+ The compiler and runtime participate in different stages of an Exa-AToW workflow:
81
+
82
+ 1. The Exa-AToW compiler reads XGTD HAPS descriptions.
83
+ 2. It generates Galaxy tools, CWL tasks, or MCP servers.
84
+ 3. The generated proxy is executed by the target workflow environment.
85
+ 4. The proxy uses `haps-invocation` to submit and monitor the HAPS job.
86
+ 5. The runtime processes the results and produces metadata for subsequent tasks.
87
+
88
+ ## Version compatibility
89
+
90
+ The Exa-AToW compiler declares the compatible runtime versions in its package dependencies. Users installing the compiler therefore receive a compatible runtime automatically.
91
+
92
+ For example:
93
+
94
+ ```toml
95
+ dependencies = [
96
+ "haps-invocation>=0.1.0,<0.2.0",
97
+ ]
98
+ ```
99
+
100
+ ## Development installation
101
+
102
+ From the `haps-invocation` directory, install the package in editable mode:
103
+
104
+ ```bash
105
+ python -m pip install -e .
106
+ ```
107
+
108
+ To build the runtime distribution:
109
+
110
+ ```bash
111
+ python -m pip install --upgrade build
112
+ python -m build
113
+ ```
114
+
115
+ The resulting wheel and source distribution are created under `dist/`.
@@ -0,0 +1,7 @@
1
+ haps_invocation/__init__.py,sha256=u6iQi8gM7uVO3HfjxEyGB41LMk847HDyoBJOQCPokxI,455
2
+ haps_invocation/invocation.py,sha256=6f7ut3bsUwZwsFCX7WImUxCt3B3dFp8UD77pEEA9dus,24772
3
+ haps_invocation-0.2.1.dist-info/licenses/LICENSE,sha256=_eYvYXFHRnA9PAl5K6b4T9fCYAgvPVzFivgSnZItUIM,1112
4
+ haps_invocation-0.2.1.dist-info/METADATA,sha256=ReRXcMr7a8WcwnfuDRWlZNMYBI4eM6J3vvdlgBzHIZU,3460
5
+ haps_invocation-0.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ haps_invocation-0.2.1.dist-info/top_level.txt,sha256=IZyw0yIZRYG_YfoJr4ng0FtEdb1GKV5TCyCXPrd3Tyw,16
7
+ haps_invocation-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sara Sadat Hoseininasab, Université de Rennes, Exa-AToW
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ haps_invocation