Repository navigation
Expand file tree
/
Copy pathPythonModuleBuilder.cs
More file actions
1876 lines (1578 loc) · 81.1 KB
/
Copy pathPythonModuleBuilder.cs
File metadata and controls
1876 lines (1578 loc) · 81.1 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
using System.Globalization;
namespace Aspire.Hosting.CodeGeneration.Python;
/// <summary>
/// Represents a builder for generating Python module structure and related code components.
/// Sections are built independently and combined in the correct order when Write() is called.
/// </summary>
internal sealed class PythonModuleBuilder
{
/// <summary>
/// Gets the enum type definitions.
/// </summary>
public StringBuilder Enums { get; } = new();
/// <summary>
/// Gets the DTO class definitions.
/// </summary>
public StringBuilder DtoClasses { get; } = new();
/// <summary>
/// Gets the exported value definitions.
/// </summary>
public StringBuilder ExportedValues { get; } = new();
/// <summary>
/// Gets the type class definitions (context types, wrapper types).
/// </summary>
public Dictionary<string, StringBuilder> TypeClasses { get; } = new();
/// <summary>
/// Gets the interface class definitions
/// </summary>
public Dictionary<string, StringBuilder> InterfaceClasses { get; } = new();
/// <summary>
/// Gets the resource class builder definitions.
/// </summary>
public Dictionary<string, StringBuilder> ResourceBuilders { get; } = new();
/// <summary>
/// Gets the resource parameter definitions
/// </summary>
public Dictionary<string, StringBuilder> ResourceOptions { get; } = new();
/// <summary>
/// A list of all keyword argument names supported for a Resource builder, used to prevent naming conflicts.
/// </summary>
public Dictionary<string, List<string>> ResourceOptionNames { get; } = new();
/// <summary>
/// Gets the resource class definitions
/// </summary>
public Dictionary<string, StringBuilder> ResourceClasses { get; } = new();
/// <summary>
/// Gets the entry point function definitions.
/// </summary>
public StringBuilder EntryPoints { get; } = new();
/// <summary>
/// Gets the handle registration definitions.
/// </summary>
public Dictionary<string, string> HandleRegistrations { get; } = new();
/// <summary>
/// Gets the method parameter type class definitions, keyed by parameter type name.
/// </summary>
public Dictionary<string, StringBuilder> MethodParameters { get; } = new();
/// <summary>
/// Writes the complete Python module content.
/// </summary>
/// <returns>The complete Python module as a string.</returns>
public string Write()
{
var output = new StringBuilder();
output.AppendLine(Header);
output.AppendLine(StandardImports);
// TODO: Not quite sure how to handle versioning, as users wont have direct control over the
// code generator version. Ideally this would reflect the .NET package version, but that will be
// painful for test snapshots, just going to hardcode a version for now.
output.AppendLine(CultureInfo.InvariantCulture, $"__version__ = \"0.1.0\"");
output.AppendLine();
output.AppendLine(Utils);
// Enums
if (Enums.Length > 0)
{
output.AppendLine();
output.AppendLine("# ============================================================================");
output.AppendLine("# Enum Types");
output.AppendLine("# ============================================================================");
output.AppendLine();
output.Append(Enums);
}
// Method parameters
if (MethodParameters.Count > 0)
{
output.AppendLine();
output.AppendLine("# ============================================================================");
output.AppendLine("# Method Parameters");
output.AppendLine("# ============================================================================");
foreach (var kvp in MethodParameters)
{
output.AppendLine();
output.Append(kvp.Value);
}
}
// DTO Classes
if (DtoClasses.Length > 0)
{
output.AppendLine();
output.AppendLine("# ============================================================================");
output.AppendLine("# DTO Classes (Data Transfer Objects)");
output.AppendLine("# ============================================================================");
output.AppendLine();
output.Append(DtoClasses);
}
if (ExportedValues.Length > 0)
{
output.AppendLine();
output.AppendLine("# ============================================================================");
output.AppendLine("# Exported Values");
output.AppendLine("# ============================================================================");
output.AppendLine();
output.Append(ExportedValues);
}
// Type Classes
if (TypeClasses.Count > 0)
{
output.AppendLine();
output.AppendLine("# ============================================================================");
output.AppendLine("# Type Classes");
output.AppendLine("# ============================================================================");
foreach (var kvp in TypeClasses)
{
output.AppendLine();
output.Append(kvp.Value);
}
}
// Interface Classes
if (InterfaceClasses.Count > 0)
{
output.AppendLine();
output.AppendLine("# ============================================================================");
output.AppendLine("# Interface Classes");
output.AppendLine("# ============================================================================");
foreach (var kvp in InterfaceClasses)
{
output.AppendLine();
output.Append(kvp.Value);
}
}
// Resource Builder Classes
if (ResourceClasses.Count > 0)
{
output.AppendLine();
output.AppendLine("# ============================================================================");
output.AppendLine("# Builder Classes");
output.AppendLine("# ============================================================================");
foreach (var kvp in ResourceClasses)
{
output.AppendLine();
output.Append(ResourceOptions[kvp.Key]);
output.AppendLine();
output.Append(kvp.Value);
}
}
// Entry Points
if (EntryPoints.Length > 0)
{
output.AppendLine();
output.AppendLine("# ============================================================================");
output.AppendLine("# Entry Point Functions");
output.AppendLine("# ============================================================================");
output.AppendLine();
output.Append(EntryPoints);
}
// Connection Helper
output.AppendLine();
output.AppendLine("# ============================================================================");
output.AppendLine("# Connection Helper");
output.AppendLine("# ============================================================================");
output.AppendLine();
output.AppendLine(ConnectionHelperCode);
// Handle Registrations
if (HandleRegistrations.Count > 0)
{
output.AppendLine();
output.AppendLine();
output.AppendLine("# ============================================================================");
output.AppendLine("# Handle Registrations");
output.AppendLine("# ============================================================================");
output.AppendLine();
output.AppendLine("_register_handle_wrapper(\"Aspire.Hosting/Aspire.Hosting.ApplicationModel.ReferenceExpression\", lambda handle, _: ReferenceExpression(handle))");
output.AppendLine("_register_handle_wrapper(\"System.Private.CoreLib/System.Threading.CancellationToken\", CancellationToken)");
foreach (var (typeId, className) in HandleRegistrations)
{
output.AppendLine(
CultureInfo.InvariantCulture,
$"_register_handle_wrapper(\"{typeId}\", {className})");
}
}
return output.ToString();
}
/// <summary>
/// The file header with copyright notice.
/// </summary>
public const string Header = """
# -------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in project root for information.
#
# This is a generated file. Any modifications may be overwritten.
# -------------------------------------------------------------
""";
/// <summary>
/// Standard Python imports for the generated SDK.
/// </summary>
public const string StandardImports = """
from __future__ import annotations
import os
import base64
import sys
import json
import logging
import secrets
import signal
import socket
import threading
import time
import abc
import datetime
import types
import typing
from functools import cached_property as _cached_property
from contextlib import AbstractContextManager
_logger = logging.getLogger(__name__)
# Maximum allowed message size (64 MB) to prevent memory exhaustion from malicious Content-Length
_MAX_MESSAGE_SIZE = 64 * 1024 * 1024
# Maximum number of headers and total header size to prevent header-flooding attacks
_MAX_HEADER_COUNT = 16
_MAX_HEADER_BYTES = 8 * 1024
# Marker string for detecting generic .NET builder type names.
_BUILDER_GENERIC_MARKER = "Builder`1["
_uncached_property = property
""";
/// <summary>
/// Utility functions for the generated SDK.
/// </summary>
public const string Utils = """
# ============================================================================
# Platform-specific Socket Implementation
# ============================================================================
if sys.platform == "win32":
import ctypes
from ctypes import wintypes
_kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
class _OVERLAPPED(ctypes.Structure):
'''Windows OVERLAPPED structure for async I/O.'''
_fields_ = [
("Internal", ctypes.POINTER(ctypes.c_ulong)),
("InternalHigh", ctypes.POINTER(ctypes.c_ulong)),
("Offset", wintypes.DWORD),
("OffsetHigh", wintypes.DWORD),
("hEvent", wintypes.HANDLE),
]
class _PipeSocket:
'''A socket-like wrapper around a Win32 named pipe using ctypes.'''
# Win32 constants
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
OPEN_EXISTING = 3
INVALID_HANDLE_VALUE = -1
FILE_FLAG_OVERLAPPED = 0x40000000
ERROR_IO_PENDING = 997
ERROR_FILE_NOT_FOUND = 2
def __init__(self, pipe_path: str) -> None:
self._handle: int | None = None
handle = _kernel32.CreateFileW(
pipe_path,
self.GENERIC_READ | self.GENERIC_WRITE,
0, # no sharing
None, # default security
self.OPEN_EXISTING,
self.FILE_FLAG_OVERLAPPED, # match server's async mode
None # no template
)
if handle == self.INVALID_HANDLE_VALUE:
error = ctypes.get_last_error()
if error == self.ERROR_FILE_NOT_FOUND:
raise FileNotFoundError(f"Pipe not found: {pipe_path}")
raise OSError(f"CreateFile failed with error {error}")
self._handle = handle
def _create_overlapped_event(self) -> _OVERLAPPED:
'''Create an OVERLAPPED structure with an event for async I/O.'''
overlapped = _OVERLAPPED()
overlapped.hEvent = _kernel32.CreateEventW(None, True, False, None)
return overlapped
def recv(self, n: int) -> bytes:
'''Read up to n bytes using overlapped I/O.'''
buffer = ctypes.create_string_buffer(n)
bytes_read = wintypes.DWORD()
overlapped = self._create_overlapped_event()
try:
success = _kernel32.ReadFile(
self._handle,
buffer,
n,
ctypes.byref(bytes_read),
ctypes.byref(overlapped)
)
if not success:
error = ctypes.get_last_error()
if error == self.ERROR_IO_PENDING:
# Wait for the operation to complete
_kernel32.GetOverlappedResult(
self._handle,
ctypes.byref(overlapped),
ctypes.byref(bytes_read),
True # wait
)
else:
raise OSError(f"ReadFile failed with error {error}")
finally:
_kernel32.CloseHandle(overlapped.hEvent)
return buffer.raw[:bytes_read.value]
def sendall(self, data: bytes) -> None:
'''Write all data using overlapped I/O.'''
bytes_written = wintypes.DWORD()
overlapped = self._create_overlapped_event()
try:
offset = 0
while offset < len(data):
chunk = data[offset:]
success = _kernel32.WriteFile(
self._handle,
chunk,
len(chunk),
ctypes.byref(bytes_written),
ctypes.byref(overlapped)
)
if not success:
error = ctypes.get_last_error()
if error == self.ERROR_IO_PENDING:
# Wait for the operation to complete
_kernel32.GetOverlappedResult(
self._handle,
ctypes.byref(overlapped),
ctypes.byref(bytes_written),
True # wait
)
else:
raise OSError(f"WriteFile failed with error {error}")
offset += bytes_written.value
finally:
_kernel32.CloseHandle(overlapped.hEvent)
def close(self) -> None:
'''Close the handle.'''
if self._handle is not None and self._handle != self.INVALID_HANDLE_VALUE:
_kernel32.CloseHandle(self._handle)
self._handle = None
def _connect_pipe(socket_path: str, timeout_sec: float) -> _PipeSocket:
'''Connect to a named pipe with timeout, retrying until available.'''
pipe_path = f"\\\\.\\pipe\\{socket_path}"
_logger.debug("Connecting to: %s", pipe_path)
start_time = time.time()
while (time.time() - start_time) < timeout_sec:
try:
return _PipeSocket(pipe_path)
except FileNotFoundError:
time.sleep(0.1)
raise TimeoutError("Connection timeout")
else:
# On Unix, use socket.socket directly as the pipe socket type
_PipeSocket = socket.socket # type: ignore[misc]
def _connect_pipe(socket_path: str, timeout_sec: float) -> _PipeSocket:
'''Connect to a Unix domain socket with timeout.'''
_logger.debug("Connecting to: %s", socket_path)
start_time = time.time()
while (time.time() - start_time) < timeout_sec:
try:
sock = _PipeSocket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(timeout_sec)
sock.connect(socket_path)
sock.settimeout(None) # Set to blocking mode
return sock
except FileNotFoundError:
time.sleep(0.1)
raise TimeoutError("Connection timeout")
# ============================================================================
# Base Types
# ============================================================================
class AtsErrorDetails(typing.TypedDict, total=False):
'''Error details for ATS errors.'''
parameter: str
expected: str
actual: str
class AtsErrorData(typing.TypedDict, total=False):
'''Structured error from ATS capability invocation.'''
code: str
message: str
capability: str
details: AtsErrorDetails
class AtsErrorCodes:
'''ATS error codes returned by the server.'''
CAPABILITY_NOT_FOUND = "CAPABILITY_NOT_FOUND"
HANDLE_NOT_FOUND = "HANDLE_NOT_FOUND"
TYPE_MISMATCH = "TYPE_MISMATCH"
INVALID_ARGUMENT = "INVALID_ARGUMENT"
ARGUMENT_OUT_OF_RANGE = "ARGUMENT_OUT_OF_RANGE"
CALLBACK_ERROR = "CALLBACK_ERROR"
INTERNAL_ERROR = "INTERNAL_ERROR"
def _simplify_type_name(typestring: str) -> str:
'''Simplify a .NET type name for readability in error messages.'''
# Collapse any embedded newlines/whitespace so patterns can match
collapsed = " ".join(typestring.split())
# Check for generic builder pattern like "IResourceBuilder`1[Namespace.Type]"
idx = collapsed.find(_BUILDER_GENERIC_MARKER)
if idx >= 0:
inner = collapsed[idx + len(_BUILDER_GENERIC_MARKER):]
# Skip any extra opening brackets (e.g. "[[")
inner = inner.lstrip("[").strip()
# Take only the qualified name (before any comma/assembly info or closing brackets)
inner = inner.split(",")[0].split("]")[0].strip()
# Get simple class name from fully-qualified name
inner_type = inner.rsplit(".", 1)[-1]
# Strip leading 'I' from interface names (e.g., IResourceWithConnectionString -> ResourceWithConnectionString)
if len(inner_type) > 1 and inner_type[0] == "I" and inner_type[1].isupper():
inner_type = inner_type[1:]
return inner_type
return typestring.split(".")[-1] # Fallback: take simple name from fully-qualified type
def _format_type_error(error: AtsErrorData) -> Exception:
'''Formats an ATS type error into a Python exception with a helpful message.'''
try:
details = error["details"] # type: ignore[index]
parameter = details["parameter"] # type: ignore[index]
expected = _simplify_type_name(details["expected"]) # type: ignore[index]
actual = _simplify_type_name(details["actual"]) # type: ignore[index]
message_prefix = ""
if capability := error.get("capability"):
message_prefix = f" in '{capability.split('/')[-1]}'"
message = f"Type mismatch{message_prefix} for parameter '{parameter}': expected {expected}, got {actual}"
return TypeError(message)
except KeyError:
if message := error.get("message"):
return TypeError(message)
if capability := error.get("capability"):
return TypeError(f"Type mismatch in capability '{capability}'")
return TypeError("Parameter type mismatch.")
def _is_ats_error(value: typing.Any) -> bool:
'''Type guard to check if a value is an ATS error response.'''
return (
isinstance(value, dict)
and "$error" in value
and isinstance(value["$error"], dict)
)
def _is_marshalled_handle(value: typing.Any) -> bool:
'''Type guard to check if a value is a marshalled handle.'''
return (
isinstance(value, dict)
and "$handle" in value
and "$type" in value
)
# ============================================================================
# Handle
# ============================================================================
class Handle:
'''
A typed handle to a .NET object in the ATS system.
Handles are opaque references that can be passed to capabilities.
'''
def __init__(self, handle_data: typing.Mapping[str, typing.Any]) -> None:
self._handle_id = handle_data["$handle"]
self._type_id = handle_data["$type"]
@property
def handle_id(self) -> str:
'''The handle ID (instance number)'''
return self._handle_id
@property
def type_id(self) -> str:
'''The ATS type ID'''
return self._type_id
def to_json(self) -> typing.Mapping[str, typing.Any]:
'''Serialize for JSON-RPC transport'''
return {
"$handle": self._handle_id,
"$type": self._type_id
}
def __repr__(self) -> str:
'''String representation for debugging'''
friendly_name = self._type_id.split("/")[-1].split(".")[-1]
return f"Handle[{friendly_name}]({self._handle_id})"
# ============================================================================
# Handle Wrapper Registry
# ============================================================================
_HandleWrapperFactory = typing.Callable[[Handle, "AspireClient"], typing.Any]
# Registry of handle wrapper factories by type ID
_handle_wrapper_registry: dict[str, _HandleWrapperFactory] = {}
def _register_handle_wrapper(type_id: str, factory: _HandleWrapperFactory) -> None:
'''
Register a wrapper factory for a type ID.
Called by generated code to register wrapper classes.
'''
_handle_wrapper_registry[type_id] = factory
def _wrap_if_handle(value: typing.Any, client: AspireClient | None = None, kwargs: typing.Mapping[str, typing.Any] | None = None) -> typing.Any:
'''
Checks if a value is a marshalled handle and wraps it appropriately.
Uses the wrapper registry to create typed wrapper instances when available.
'''
if isinstance(value, dict) and _is_marshalled_handle(value):
handle = Handle(value)
type_id = value["$type"]
# Try to find a registered wrapper factory for this type
if type_id and client:
factory = _handle_wrapper_registry.get(type_id)
if factory:
if kwargs:
return factory(handle, client, **kwargs)
return factory(handle, client)
return handle
return value
# ============================================================================
# Errors
# ============================================================================
class AspireError(Exception):
'''Base class for Aspire errors.'''
error: AtsErrorData
def __init__(self, error: AtsErrorData) -> None:
super().__init__(error.get("message", "Unknown error"))
self.error = error
@property
def code(self) -> str:
'''Machine-readable error code'''
return self.error.get("code", "UNKNOWN")
@property
def capability(self) -> str | None:
'''The capability that failed (if applicable)'''
return self.error.get("capability")
class OperationCancelled(Exception):
'''Error thrown when a cancellation token is invoked.'''
pass
# ============================================================================
# JSON Encoder
# ============================================================================
@typing.runtime_checkable
class _ReferenceHandle(typing.Protocol):
'''Protocol for objects that have a handle property.'''
@property
def handle(self) -> Handle:
...
def _timedelta_as_isostr(td: datetime.timedelta) -> str:
'''Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S'
Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython
:param td: The timedelta object to convert
:type td: datetime.timedelta
:return: An ISO 8601 formatted string representing the timedelta object
:rtype: str
'''
# Split seconds to larger units
seconds = td.total_seconds()
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
days, hours, minutes = list(map(int, (days, hours, minutes)))
seconds = round(seconds, 6)
# Build date
date_str = ""
if days:
date_str = "%sD" % days
# Build time
time_str = "T"
# Hours
bigger_exists = date_str or hours
if bigger_exists:
time_str += "{:02}H".format(hours)
# Minutes
bigger_exists = bigger_exists or minutes
if bigger_exists:
time_str += "{:02}M".format(minutes)
# Seconds
try:
if seconds.is_integer():
seconds_string = "{:02}".format(int(seconds))
else:
# 9 chars long w/ leading 0, 6 digits after decimal
seconds_string = "%09.6f" % seconds
# Remove trailing zeros
seconds_string = seconds_string.rstrip("0")
except AttributeError: # int.is_integer() raises
seconds_string = "{:02}".format(seconds)
time_str += "{}S".format(seconds_string)
return "P" + date_str + time_str
def _datetime_as_isostr(dt: typing.Union[datetime.datetime, datetime.date, datetime.time, datetime.timedelta]) -> str:
'''Converts a datetime.(datetime|date|time|timedelta) object into an ISO 8601 formatted string.
:param dt: The datetime object to convert
:type dt: datetime.datetime or datetime.date or datetime.time or datetime.timedelta
:return: An ISO 8601 formatted string representing the datetime object
:rtype: str
'''
# First try datetime.datetime
if hasattr(dt, "year") and hasattr(dt, "hour"):
dt = typing.cast(datetime.datetime, dt)
# astimezone() fails for naive times in Python 2.7, so make make sure dt is aware (tzinfo is set)
if not dt.tzinfo:
iso_formatted = dt.replace(tzinfo=datetime.timezone.utc).isoformat()
else:
iso_formatted = dt.astimezone(datetime.timezone.utc).isoformat()
# Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt)
return iso_formatted.replace("+00:00", "Z")
# Next try datetime.date or datetime.time
try:
dt = typing.cast(typing.Union[datetime.date, datetime.time], dt)
return dt.isoformat()
# Last, try datetime.timedelta
except AttributeError:
dt = typing.cast(datetime.timedelta, dt)
return _timedelta_as_isostr(dt)
class _AspireJSONEncoder(json.JSONEncoder):
'''A JSON encoder that's capable of serializing datetime objects and bytes.'''
def default(self, o: typing.Any) -> typing.Any:
'''Override the default method to handle datetime and bytes serialization.
:param o: The object to serialize.
:type o: Any
:return: A JSON-serializable representation of the object.
:rtype: Any
'''
if isinstance(o, ReferenceExpression):
return o.to_json()
if isinstance(o, _ReferenceHandle):
return o.handle.to_json()
if isinstance(o, Handle):
return o.to_json()
if isinstance(o, (bytes, bytearray)):
return base64.b64encode(o).decode()
try:
return _datetime_as_isostr(o)
except AttributeError:
pass
return super().default(o)
class AspireClient:
'''Client for connecting to the Aspire AppHost via socket/named pipe (synchronous with threads).'''
# Default heartbeat interval in seconds
DEFAULT_HEARTBEAT_INTERVAL = 5.0
def __init__(self, socket_path: str, *, debug: bool | None = None, heartbeat_interval: float | None = None) -> None:
self.socket_path = socket_path
self.debug = debug if debug is not None else False
self._socket: _PipeSocket | None = None
self._request_id = 0
self._pending_requests: dict[int, threading.Event] = {}
self._pending_results: dict[int, tuple[typing.Any, Exception | None]] = {}
self._disconnect_callbacks: list[typing.Callable[[], None]] = []
self._receive_thread: threading.Thread | None = None
self._heartbeat_thread: threading.Thread | None = None
self._cancellation_threads: dict[str, tuple[typing.Callable[[], None], threading.Thread]] = {}
self._cancellation_id = 0
self._heartbeat_interval = heartbeat_interval if heartbeat_interval is not None else self.DEFAULT_HEARTBEAT_INTERVAL
self._heartbeat_stop_event = threading.Event()
self._connected = False
self._connection_error: ConnectionError | None = None
self._lock = threading.Lock()
self._callback_registry: dict[str, typing.Callable[..., typing.Any]] = {}
self._callback_id_counter = 0
self._callback_threads: dict[str, threading.Thread] = {}
def on_disconnect(self, callback: typing.Callable[[], None]) -> None:
'''Register a callback to be called when the connection is lost'''
with self._lock:
self._disconnect_callbacks.append(callback)
def _handle_sigint(self, signum: int, frame: typing.Any) -> None:
'''Handle SIGINT (Ctrl+C) by cancelling all pending requests and closing connection.'''
# Close the connection
self._close_connection(ConnectionError("Shutdown by user"))
# TODO: This will just shutdown the process, which may be best as this will likely
# be run with aspire.run, which will prefer a quick exit with zero exit code.
# Not entirely sure if this signal will be propagated correctly by .NET.... well see.
sys.exit(0)
def _close_connection(self, error: ConnectionError | None = None) -> None:
'''
Central method for closing the connection. Thread-safe and idempotent.
Args:
error: If provided, this is an unexpected disconnection and callbacks
will be notified. If None, this is an intentional disconnect.
This method:
- Closes the socket
- Sets _connected = False
- Stores the error (if provided and not already set)
- Signals the heartbeat thread to stop
- Notifies disconnect callbacks (only on first unexpected disconnection)
'''
should_notify = False
callbacks: list[typing.Callable[[], None]] = []
with self._lock:
# Close socket if open
if self._socket is not None:
try:
self._socket.close()
except Exception:
pass
self._socket = None
# Mark as disconnected
should_notify = self._connected
self._connected = False
callbacks = list(self._disconnect_callbacks)
if should_notify:
if error:
_logger.error("Closing connection to AppHost with error: %s", error)
else:
_logger.info("Closing connection to AppHost")
# Handle error state
if error is not None:
# Unexpected disconnection - store error if first failure
if self._connection_error is None:
self._connection_error = error
else:
# Intentional disconnect - clear any previous error?
self._connection_error = None
for event in self._pending_requests.values():
event.set()
for (cancellation, _ ) in self._cancellation_threads.values():
# Threads will exit on their own when they notice disconnection
cancellation()
# Signal heartbeat to stop (outside lock, it's thread-safe)
self._heartbeat_stop_event.set()
# Notify callbacks outside lock to avoid deadlocks
if should_notify:
for callback in callbacks:
try:
callback()
except Exception:
pass
def connect(self, timeout_ms: int = 10000) -> None:
'''Connect to the Aspire AppHost'''
timeout_sec = timeout_ms / 1000.0
socket = _connect_pipe(self.socket_path, timeout_sec)
with self._lock:
self._socket = socket
self._connected = True
self._connection_error = None
self._heartbeat_stop_event.clear()
# Install SIGINT handler for clean Ctrl+C handling
signal.signal(signal.SIGINT, self._handle_sigint)
_logger.info("Connected to AppHost")
# Start receiving messages in a background thread
self._receive_thread = threading.Thread(target=self._receive_loop, daemon=True)
self._receive_thread.start()
# Start heartbeat thread to monitor connection health
self._heartbeat_thread = threading.Thread(target=self._heartbeat_loop, daemon=True)
self._heartbeat_thread.start()
def _recv_exactly(self, n: int) -> bytes:
'''Read exactly n bytes from the socket'''
data = b""
while len(data) < n:
chunk = typing.cast(_PipeSocket, self._socket).recv(n - len(data))
if not chunk:
raise ConnectionError("Connection closed")
data += chunk
return data
def _read_line(self) -> bytes:
'''Read a line ending with \\r\\n from the socket'''
line = b""
while True:
byte = typing.cast(_PipeSocket, self._socket).recv(1)
if not byte:
raise ConnectionError("Connection closed")
line += byte
if line.endswith(b"\r\n"):
return line[:-2] # Remove \r\n
def _read_headers(self) -> dict[str, str]:
'''Read HTTP-style headers until empty line.
Enforces limits on header count and total size to prevent
memory exhaustion from a malicious peer.
'''
headers: dict[str, str] = {}
total_bytes = 0
while True:
line = self._read_line()
if not line: # Empty line signals end of headers
break
total_bytes += len(line) + 2 # account for \r\n
if len(headers) >= _MAX_HEADER_COUNT:
raise ConnectionError(f"Too many headers (limit {_MAX_HEADER_COUNT})")
if total_bytes > _MAX_HEADER_BYTES:
raise ConnectionError(f"Headers too large (limit {_MAX_HEADER_BYTES} bytes)")
# Parse "Header-Name: value"
if b":" in line:
name, value = line.split(b":", 1)
headers[name.decode("utf-8").strip().lower()] = value.decode("utf-8").strip()
return headers
def _receive_loop(self) -> None:
'''Receive and process messages from the server'''
try:
while self._connected and self._socket:
# Read HTTP-style headers (HeaderDelimitedMessageHandler format)
headers = self._read_headers()
content_length = int(headers.get("content-length", "0"))
if content_length == 0:
continue
if content_length > _MAX_MESSAGE_SIZE:
raise ConnectionError(
f"Message too large: {content_length} bytes "
f"(limit {_MAX_MESSAGE_SIZE} bytes)"
)
# Read message content
message_bytes = self._recv_exactly(content_length)
message_str = message_bytes.decode("utf-8")
message = json.loads(message_str)
if self.debug:
if message.get("result") == "pong":
_logger.debug("<- %s", message)
else:
_logger.info("<- %s", message)
# Handle response or request
if "method" in message:
# This is a request from the server (callback invocation)
self._handle_server_request(message)
elif "id" in message:
# This is a response to our request
request_id = message["id"]
with self._lock:
if request_id in self._pending_requests:
event = self._pending_requests[request_id]
if "error" in message:
self._pending_results[request_id] = (None, Exception(message["error"]["message"]))
else:
self._pending_results[request_id] = (message.get("result"), None)
event.set()
except AttributeError:
# This probably means the socket was closed
pass
except ConnectionError as e:
self._close_connection(e)
except Exception as e:
self._close_connection(ConnectionError(f"Receive loop error: {e}"))
def _heartbeat_loop(self) -> None:
'''Periodically ping the server to check connection health.'''
while not self._heartbeat_stop_event.wait(timeout=self._heartbeat_interval):
with self._lock:
if not self._connected:
break
try:
self.ping()
except Exception as e:
self._close_connection(ConnectionError(f"Heartbeat failed: {e}"))
break
def _handle_server_request(self, message: dict[str, typing.Any]) -> None:
'''Handle a request from the server (e.g., callback invocation)'''
method = message.get("method")
request_id = message.get("id")
params = message.get("params", [])