| | | 1 | | using Kestrun.Hosting; |
| | | 2 | | using Kestrun.Models; |
| | | 3 | | using Python.Runtime; |
| | | 4 | | using Serilog.Events; |
| | | 5 | | |
| | | 6 | | namespace Kestrun.Languages; |
| | | 7 | | // --------------------------------------------------------------------------- |
| | | 8 | | // Python delegate builder – now takes optional imports / references |
| | | 9 | | // --------------------------------------------------------------------------- |
| | | 10 | | |
| | | 11 | | internal static class PyDelegateBuilder |
| | | 12 | | { |
| | 2 | 13 | | public static bool Implemented { get; set; } |
| | 0 | 14 | | public static void ConfigurePythonRuntimePath(string path) => Python.Runtime.Runtime.PythonDLL = path; |
| | | 15 | | // --------------------------------------------------------------------------- |
| | | 16 | | // helpers at class level |
| | | 17 | | // --------------------------------------------------------------------------- |
| | | 18 | | |
| | | 19 | | #if NET9_0_OR_GREATER |
| | | 20 | | private static readonly Lock _pyGate = new(); |
| | | 21 | | #else |
| | 1 | 22 | | private static readonly object _pyGate = new(); |
| | | 23 | | #endif |
| | | 24 | | private static bool _pyInit; |
| | | 25 | | |
| | | 26 | | private static void EnsurePythonEngine() |
| | | 27 | | { |
| | 0 | 28 | | if (_pyInit) |
| | | 29 | | { |
| | 0 | 30 | | return; |
| | | 31 | | } |
| | | 32 | | |
| | 0 | 33 | | lock (_pyGate) |
| | | 34 | | { |
| | 0 | 35 | | if (_pyInit) |
| | | 36 | | { |
| | 0 | 37 | | return; // double-check |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | // If you need a specific DLL, set Runtime.PythonDLL |
| | | 41 | | // or expose it via the PYTHONNET_PYDLL environment variable. |
| | | 42 | | // Runtime.PythonDLL = @"C:\Python312\python312.dll"; |
| | | 43 | | |
| | 0 | 44 | | PythonEngine.Initialize(); // load CPython once |
| | 0 | 45 | | _ = PythonEngine.BeginAllowThreads(); // let other threads run |
| | 0 | 46 | | _pyInit = true; |
| | 0 | 47 | | } |
| | 0 | 48 | | } |
| | | 49 | | internal static RequestDelegate Build(KestrunHost host, string code) |
| | | 50 | | { |
| | 1 | 51 | | var logger = host.Logger; |
| | 1 | 52 | | if (logger.IsEnabled(LogEventLevel.Debug)) |
| | | 53 | | { |
| | 1 | 54 | | logger.Debug("Building Python delegate, script l ength={Length}", code?.Length); |
| | | 55 | | } |
| | | 56 | | |
| | 1 | 57 | | if (string.IsNullOrWhiteSpace(code)) |
| | | 58 | | { |
| | 0 | 59 | | throw new ArgumentException("Python script code cannot be empty.", nameof(code)); |
| | | 60 | | } |
| | | 61 | | |
| | 1 | 62 | | if (!Implemented) |
| | | 63 | | { |
| | 1 | 64 | | throw new NotImplementedException("Python scripting is not yet supported in Kestrun."); |
| | | 65 | | } |
| | | 66 | | |
| | 0 | 67 | | EnsurePythonEngine(); // one-time init |
| | | 68 | | |
| | | 69 | | // ---------- compile the script once ---------- |
| | 0 | 70 | | using var gil = Py.GIL(); // we are on the caller's thread |
| | 0 | 71 | | using var scope = Py.CreateScope(); |
| | | 72 | | |
| | | 73 | | /* Expect the user script to contain: |
| | | 74 | | |
| | | 75 | | def handle(ctx, res): |
| | | 76 | | # ctx -> ASP.NET HttpContext (proxied) |
| | | 77 | | # res -> KestrunResponse (proxied) |
| | | 78 | | ... |
| | | 79 | | |
| | | 80 | | Scope.Exec compiles & executes that code once per route. |
| | | 81 | | */ |
| | 0 | 82 | | _ = scope.Exec(code); |
| | 0 | 83 | | dynamic pyHandle = scope.Get("handle"); |
| | | 84 | | |
| | | 85 | | // ---------- return a RequestDelegate ---------- |
| | 0 | 86 | | return async context => |
| | 0 | 87 | | { |
| | 0 | 88 | | try |
| | 0 | 89 | | { |
| | 0 | 90 | | using var _ = Py.GIL(); // enter GIL for *this* request |
| | 0 | 91 | | var krRequest = await KestrunRequest.NewRequest(context); |
| | 0 | 92 | | var krResponse = new KestrunResponse(krRequest); |
| | 0 | 93 | | |
| | 0 | 94 | | // Call the Python handler (Python → .NET marshal is automatic) |
| | 0 | 95 | | pyHandle(context, krResponse, context); |
| | 0 | 96 | | |
| | 0 | 97 | | // redirect? |
| | 0 | 98 | | if (!string.IsNullOrEmpty(krResponse.RedirectUrl)) |
| | 0 | 99 | | { |
| | 0 | 100 | | context.Response.Redirect(krResponse.RedirectUrl); |
| | 0 | 101 | | return; // finally-block will CompleteAsync |
| | 0 | 102 | | } |
| | 0 | 103 | | |
| | 0 | 104 | | // normal response |
| | 0 | 105 | | await krResponse.ApplyTo(context.Response).ConfigureAwait(false); |
| | 0 | 106 | | } |
| | 0 | 107 | | catch (Exception ex) |
| | 0 | 108 | | { |
| | 0 | 109 | | // optional logging |
| | 0 | 110 | | logger.Error($"Python route error: {ex}"); |
| | 0 | 111 | | context.Response.StatusCode = 500; |
| | 0 | 112 | | context.Response.ContentType = "text/plain; charset=utf-8"; |
| | 0 | 113 | | await context.Response.WriteAsync( |
| | 0 | 114 | | "Python script failed while processing the request.").ConfigureAwait(false); |
| | 0 | 115 | | } |
| | 0 | 116 | | finally |
| | 0 | 117 | | { |
| | 0 | 118 | | // Always flush & close so the client doesn’t hang |
| | 0 | 119 | | try { await context.Response.CompleteAsync().ConfigureAwait(false); } |
| | 0 | 120 | | catch (ObjectDisposedException) { /* client disconnected */ } |
| | 0 | 121 | | } |
| | 0 | 122 | | }; |
| | 0 | 123 | | } |
| | | 124 | | } |