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