Asynchronous Sessions¶
AsyncSession is the native asynchronous counterpart to Session. It uses a
native httpx2.AsyncClient; it is not a synchronous client wrapped in an event
loop. Use it inside an existing async application and close it with async with.
Return shapes and parity¶
The async methods preserve the synchronous result contracts:
| Method | Result |
|---|---|
await fetch(kind=None, status=None) |
list[dict[str, str]] |
await create(...) |
list[str] containing the IDs that launched successfully |
await info(ids) |
list[dict[str, Any]] |
await logs(ids, verbose=False) |
dict[str, str], or None when verbose=True |
await events(ids, verbose=False) |
list[dict[str, str]], or None when verbose=True |
await destroy(ids) / await destroy_with(...) |
dict[str, bool] |
await renew(ids) |
dict[str, bool] |
await connect(ids) |
None; opens ready Session URLs |
By default, create() omits failed launches and returns [] when every launch
fails; pass errors="raise" to raise instead (see
Raise on failures). Invalid request values raise before
the HTTP request. Verbose logs and events
are sent to the canfar.sessions logger and return None.
stats() returns aggregate Science Platform Server resource statistics.
Async workflow¶
from canfar.sessions import AsyncSession
async def main() -> None:
async with AsyncSession() as session:
ids = await session.create(
name="async-analysis",
image="images.canfar.net/skaha/astroml:latest",
kind="notebook",
)
if ids:
await session.connect(ids)
print(await session.fetch(kind="notebook", status="Running"))
print(await session.info(ids))
print(await session.logs(ids))
print(await session.events(ids))
print(await session.destroy(ids))
For a headless Session, add cmd, args, and env. cores and ram request
fixed resources; omitting them uses the Science Platform Server's flexible
allocation policy.
Select Sessions for cleanup¶
destroy_with is keyword-only after prefix:
async with AsyncSession() as session:
result = await session.destroy_with(
"batch-",
kind="headless",
status="Completed",
)
Its signature is
destroy_with(prefix, *, kind="headless", status="Completed", errors=None).
Literal prefixes are anchored at the beginning; prefixes containing regular
expression metacharacters are treated as regular expressions.
Renew an interactive Session¶
renew() resets the lifetime of interactive Sessions before they
expire. Renewals run concurrently:
async with AsyncSession() as session:
print(await session.renew(["hjko98yghj", "ikvp1jtp"]))
Raise on failures¶
errors="raise" behaves as in the synchronous client:
every request runs, then SessionRequestError carries results and the
per-ID (or per-replica) errors:
from canfar.exceptions.session import SessionRequestError
async with AsyncSession(errors="raise") as session:
try:
await session.renew(["hjko98yghj", "ikvp1jtp"])
except SessionRequestError as err:
print(err.results, err.errors)
To share one httpx2.AsyncBaseTransport across clients, see
Share a connection pool.
Bases: HTTPClient
Asynchronous CANFAR Session Management Client.
This class provides methods to manage sessions in the system, including fetching session details, creating new sessions, retrieving logs, renewing and destroying existing sessions.
This class is a subclass of the HTTPClient class and inherits its
attributes and methods.
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession(
url="https://ws-uv.canfar.net/skaha",
token="token",
timeout=30,
concurrency=100,
)
Source code in canfar/sessions.py
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 | |
connect
async
¶
connect(ids)
Connect to a session[s] in a web browser.
| PARAMETER | DESCRIPTION |
|---|---|
ids
|
Session ID[s].
TYPE:
|
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession()
>>> await session.connect(ids="hjko98yghj")
>>> await session.connect(ids=["hjko98yghj", "ikvp1jtp"])
Source code in canfar/sessions.py
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 | |
create
async
¶
create(
name,
image=None,
cores=None,
ram=None,
kind="headless",
gpu=None,
cmd=None,
args=None,
env=None,
replicas=1,
*,
errors=None,
)
Launch a canfar session.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Domain request or a unique name for the Session.
TYPE:
|
image
|
Container Image when
TYPE:
|
cores
|
Number of cores. Defaults to None, i.e. flexible mode.
TYPE:
|
ram
|
Amount of RAM (GB). Defaults to None, i.e. flexible mode.
TYPE:
|
kind
|
Type of canfar session. Defaults to "headless".
TYPE:
|
gpu
|
Number of GPUs. Defaults to None.
TYPE:
|
cmd
|
Command to run. Defaults to None.
TYPE:
|
args
|
Arguments to the command. Defaults to None.
TYPE:
|
env
|
Environment variables to inject. Defaults to None.
TYPE:
|
replicas
|
Number of sessions to launch. Defaults to 1.
TYPE:
|
errors
|
Failure policy for this call. Defaults to the client's
TYPE:
|
Notes
- If cores and ram are not specified, the Session uses the Server's flexible resource allocation policy. Limits depend on the Server.
- The name of the session suffixed with the replica number. eg. test-42 when replicas > 1.
- Each container will have the following environment variables injected:
- REPLICA_ID - The replica number
- REPLICA_COUNT - The total number of replicas
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
List[str]: Session IDs for launched sessions. With |
| RAISES | DESCRIPTION |
|---|---|
SessionRequestError
|
If |
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession()
>>> await session.create(
name="test",
image='images.canfar.net/skaha/terminal:1.1.1',
cores=2,
ram=8,
gpu=1,
kind="headless",
cmd="env",
env={"TEST": "test"},
replicas=2,
)
>>> ["hjko98yghj", "ikvp1jtp"]
Source code in canfar/sessions.py
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 | |
destroy
async
¶
destroy(ids, *, errors=None)
Destroy session[s].
| PARAMETER | DESCRIPTION |
|---|---|
ids
|
Session ID[s].
TYPE:
|
errors
|
Failure policy for this call. Defaults to the client's
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, bool]
|
Dict[str, bool]: A dictionary of session IDs |
dict[str, bool]
|
and a bool indicating if the session was destroyed. |
| RAISES | DESCRIPTION |
|---|---|
SessionRequestError
|
If |
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession()
>>> await session.destroy(ids="hjko98yghj")
>>> await session.destroy(ids=["hjko98yghj", "ikvp1jtp"])
Source code in canfar/sessions.py
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 | |
destroy_with
async
¶
destroy_with(prefix, *, kind='headless', status='Completed', errors=None)
Destroy session[s] matching a prefix or regex pattern.
| PARAMETER | DESCRIPTION |
|---|---|
prefix
|
Prefix to match. Treated literally unless regex meta-characters are found.
TYPE:
|
kind
|
Type of session. Defaults to "headless".
TYPE:
|
status
|
Status of the session. Defaults to "Completed".
TYPE:
|
errors
|
Failure policy for the deletions. Defaults to the client's
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, bool]
|
Dict[str, bool]: A dictionary of session IDs |
dict[str, bool]
|
and a bool indicating if the session was destroyed. |
| RAISES | DESCRIPTION |
|---|---|
SessionRequestError
|
If |
Notes
- If the value contains regex metacharacters (e.g.,
.^$*+?{}[]()|), it is treated as a regex with :func:re.search. - Otherwise it is treated as a literal prefix (anchored with
^). This method is useful for destroying multiple sessions at once.
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession()
>>> await session.destroy_with(prefix="test") # literal prefix
>>> await session.destroy_with(prefix="desktop$") # regex
Source code in canfar/sessions.py
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 | |
events
async
¶
events(ids, verbose=False, *, errors=None)
Get deployment events for a session[s].
| PARAMETER | DESCRIPTION |
|---|---|
ids
|
Session ID[s].
TYPE:
|
verbose
|
Send events to the
TYPE:
|
errors
|
Failure policy for this call. Defaults to the client's
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[dict[str, str]] | None
|
Optional[List[Dict[str, str]]]: A list of events for the session[s]. |
| RAISES | DESCRIPTION |
|---|---|
SessionRequestError
|
If |
Notes
Configure application logging to display verbose events. Their output follows the configured handlers, rather than printing to stdout.
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession()
>>> await session.events(ids="hjko98yghj")
>>> await session.events(ids=["hjko98yghj", "ikvp1jtp"])
Source code in canfar/sessions.py
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 | |
fetch
async
¶
fetch(kind=None, status=None)
List open sessions for the user.
| PARAMETER | DESCRIPTION |
|---|---|
kind
|
Session kind. Defaults to None.
TYPE:
|
status
|
Session status. Defaults to None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list
|
Sessions information.
TYPE:
|
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession()
>>> await session.fetch(kind="notebook")
[{'id': 'vl91sfzz',
'userid': 'brars',
'runAsUID': '166169204',
'runAsGID': '166169204',
'supplementalGroups': [34241,
34337,
35124,
36227,
1902365706,
1454823273,
1025424273],
'appid': '<none>',
'image': 'image-server/repo/image:version',
'type': 'notebook',
'status': 'Running',
'name': 'notebook1',
'startTime': '2025-03-05T21:48:29Z',
'expiryTime': '2025-03-09T21:48:29Z',
'connectURL': 'https://canfar.net/session/notebook/some/url',
'requestedRAM': '8G',
'requestedCPUCores': '2',
'requestedGPUCores': '0',
'ramInUse': '<none>',
'gpuRAMInUse': '<none>',
'cpuCoresInUse': '<none>',
'gpuUtilization': '<none>'}]
Source code in canfar/sessions.py
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 | |
info
async
¶
info(ids, *, errors=None)
Get information about session[s].
| PARAMETER | DESCRIPTION |
|---|---|
ids
|
Session ID[s].
TYPE:
|
errors
|
Failure policy for this call. Defaults to the client's
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[dict[str, Any]]
|
list[dict[str, Any]]: Session information. |
| RAISES | DESCRIPTION |
|---|---|
SessionRequestError
|
If |
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession()
>>> await session.info(ids="hjko98yghj")
>>> await session.info(ids=["hjko98yghj", "ikvp1jtp"])
Source code in canfar/sessions.py
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 | |
logs
async
¶
logs(ids, verbose=False, *, errors=None)
Get logs from a session[s].
| PARAMETER | DESCRIPTION |
|---|---|
ids
|
Session ID[s].
TYPE:
|
verbose
|
Send logs to the
TYPE:
|
errors
|
Failure policy for this call. Defaults to the client's
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, str] | None
|
Dict[str, str]: Logs in text/plain format. |
| RAISES | DESCRIPTION |
|---|---|
SessionRequestError
|
If |
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession()
>>> await session.logs(ids="hjko98yghj")
>>> await session.logs(ids=["hjko98yghj", "ikvp1jtp"])
Source code in canfar/sessions.py
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 | |
renew
async
¶
renew(ids, *, errors=None)
Renew interactive session[s], resetting their lifetime.
| PARAMETER | DESCRIPTION |
|---|---|
ids
|
Session ID[s].
TYPE:
|
errors
|
Failure policy for this call. Defaults to the client's
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, bool]
|
Dict[str, bool]: A dictionary of session IDs |
dict[str, bool]
|
and a bool indicating if the session was renewed. |
| RAISES | DESCRIPTION |
|---|---|
SessionRequestError
|
If |
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession()
>>> await session.renew(ids="hjko98yghj")
>>> await session.renew(ids=["hjko98yghj", "ikvp1jtp"])
Source code in canfar/sessions.py
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 | |
stats
async
¶
stats()
Get statistics for the canfar cluster.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Dict[str, Any]: Cluster statistics, unchanged from the server.
The optional |
Examples:
>>> from canfar.sessions import AsyncSession
>>> session = AsyncSession()
>>> await session.stats()
{'cores': {'requestedCPUCores': 377,
'coresAvailable': 960,
'maxCores': {'cores': 32, 'withRam': '147Gi'}},
'ram': {'maxRAM': {'ram': '226Gi', 'withCores': 32}}}
Source code in canfar/sessions.py
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 | |