Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 51a1c3c

Browse filesBrowse files
committed
Use LambdaBootstrap and create a mock ILambdaRuntime for dotnetcore2.1
1 parent 290e82c commit 51a1c3c
Copy full SHA for 51a1c3c

File tree

Expand file treeCollapse file tree

3 files changed

+225
-74
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

3 files changed

+225
-74
lines changed
Open diff view settings
Collapse file

‎dotnetcore2.1/run/MockBootstraps/MockLambdaContext.cs‎

Copy file name to clipboardExpand all lines: dotnetcore2.1/run/MockBootstraps/MockLambdaContext.cs
-15Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ public MockLambdaContext(string handler, string eventBody)
1515
RequestId = Guid.NewGuid().ToString();
1616
StartTime = DateTime.Now;
1717
InputStream = new MemoryStream();
18-
OutputStream = new MemoryStream();
1918

2019
var eventData = Encoding.UTF8.GetBytes(eventBody);
2120
InputStream.Write(eventData, 0, eventData.Length);
@@ -44,20 +43,6 @@ public TimeSpan RemainingTime()
4443

4544
public Stream InputStream { get; }
4645

47-
public Stream OutputStream { get; }
48-
49-
public string OutputText
50-
{
51-
get
52-
{
53-
OutputStream.Position = 0;
54-
using (TextReader reader = new StreamReader(OutputStream))
55-
{
56-
return reader.ReadToEnd();
57-
}
58-
}
59-
}
60-
6146
public string RequestId { get; }
6247
public DateTime StartTime { get; }
6348

Collapse file
+217Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
using AWSLambda.Internal.Bootstrap.Context;
2+
using AWSLambda.Internal.Bootstrap.Interop.Structures;
3+
using MockLambdaRuntime;
4+
using System;
5+
using System.Collections;
6+
using System.IO;
7+
using System.Linq;
8+
using System.Runtime.InteropServices;
9+
using System.Text;
10+
11+
namespace AWSLambda.Internal.Bootstrap
12+
{
13+
internal class MockRuntime : ILambdaRuntime
14+
{
15+
private const string STACK_TRACE_INDENT = " ";
16+
17+
private bool invoked;
18+
19+
private Exception invokeError;
20+
21+
private readonly byte[] outputBuffer = new byte[SBSharedMem.SizeOfEventBody];
22+
23+
private readonly IntPtr sharedMem = Marshal.AllocHGlobal(SBSharedMem.UnmanagedStructSize);
24+
25+
private SBSharedMem curSBSharedMem;
26+
27+
private readonly MockLambdaContext context;
28+
29+
public IEnvironment Environment { get; } = new SystemEnvironment();
30+
31+
public IXRayProfiler XRayProfiler { get; } = new MockXRayProfiler();
32+
33+
public InitData InitData
34+
{
35+
get;
36+
private set;
37+
}
38+
39+
public MockRuntime(string handler, string body)
40+
{
41+
context = new MockLambdaContext(handler, body);
42+
InitData = new InitData
43+
{
44+
Handler = handler,
45+
InvokeId = context.RequestId,
46+
SuppressUserCodeInit = false,
47+
ErrorCode = null
48+
};
49+
invoked = false;
50+
}
51+
52+
public bool KeepInvokeLoopRunning()
53+
{
54+
return true;
55+
}
56+
57+
public void Init()
58+
{
59+
}
60+
61+
public InvokeData ReceiveInvoke(IDictionary initialEnvironmentVariables, RuntimeReceiveInvokeBuffers buffers)
62+
{
63+
Console.Error.WriteLine($"START RequestId: {context.RequestId} Version: {context.FunctionVersion}");
64+
65+
invoked = true;
66+
67+
curSBSharedMem = new SBSharedMem(sharedMem);
68+
return new InvokeData(curSBSharedMem)
69+
{
70+
RequestId = context.RequestId,
71+
AwsCredentials = new AwsCredentials
72+
{
73+
AccessKeyId = EnvHelper.GetOrDefault("AWS_ACCESS_KEY_ID", "SOME_ACCESS_KEY_ID"),
74+
SecretAccessKey = EnvHelper.GetOrDefault("AWS_SECRET_ACCESS_KEY", "SOME_SECRET_ACCESS_KEY"),
75+
SessionToken = System.Environment.GetEnvironmentVariable("AWS_SESSION_TOKEN")
76+
},
77+
XAmznTraceId = EnvHelper.GetOrDefault("_X_AMZN_TRACE_ID", ""),
78+
InputStream = context.InputStream,
79+
OutputStream = new MemoryStream(outputBuffer),
80+
LambdaContextInternal = new LambdaContextInternal(
81+
context.RemainingTime,
82+
SendCustomerLogMessage,
83+
new Lazy<CognitoClientContextInternal>(),
84+
context.RequestId,
85+
new Lazy<string>(context.Arn),
86+
new Lazy<string>(string.Empty),
87+
new Lazy<string>(string.Empty),
88+
initialEnvironmentVariables
89+
)
90+
};
91+
}
92+
93+
/// Try to log everything to stderr except the function result
94+
public void SendCustomerLogMessage(string message)
95+
{
96+
Console.Error.WriteLine(message);
97+
}
98+
99+
public void ReportDone(string invokeId, string errorType, bool waitForExit)
100+
{
101+
if (!invoked) return;
102+
103+
Console.Error.WriteLine($"END RequestId: {context.RequestId}");
104+
105+
Console.Error.WriteLine($"REPORT RequestId {context.RequestId}\t" +
106+
$"Duration: {context.Duration} ms\t" +
107+
$"Billed Duration: {context.BilledDuration} ms\t" +
108+
$"Memory Size {context.MemorySize} MB\t" +
109+
$"Max Memory Used: {context.MemoryUsed / (1024 * 1024)} MB");
110+
111+
if (invokeError != null)
112+
{
113+
Console.Error.WriteLine(invokeError);
114+
System.Environment.Exit(1);
115+
return;
116+
}
117+
118+
var output = Encoding.UTF8.GetString(outputBuffer, 0, curSBSharedMem.ResponseBodyLen);
119+
120+
Console.WriteLine(output);
121+
122+
System.Environment.Exit(string.IsNullOrEmpty(errorType) ? 0 : 1);
123+
}
124+
125+
public void ReportError(string invokeId, ExceptionResponse exceptionResponse)
126+
{
127+
invokeError = exceptionResponse.OriginalException;
128+
129+
// XXX: For the future perhaps:
130+
/*
131+
StringBuilder stringBuilder = new StringBuilder();
132+
if (!string.IsNullOrEmpty(exceptionResponse.StackTrace))
133+
{
134+
stringBuilder.AppendLine(exceptionResponse.StackTrace);
135+
}
136+
if (exceptionResponse.InnerException != null)
137+
{
138+
AppendStackTraceToStringBuilder(stringBuilder, exceptionResponse.InnerException);
139+
}
140+
*/
141+
}
142+
143+
private static void AppendStackTraceToStringBuilder(StringBuilder builder, ExceptionResponse ex)
144+
{
145+
if (!string.IsNullOrWhiteSpace(ex.StackTrace))
146+
{
147+
string[] array = (from s in ex.StackTrace.Split(new string[]
148+
{
149+
System.Environment.NewLine
150+
}, StringSplitOptions.None)
151+
select s.Trim() into s
152+
where !string.IsNullOrWhiteSpace(s)
153+
select STACK_TRACE_INDENT + s).ToArray();
154+
foreach (string value in array)
155+
{
156+
builder.AppendLine(value);
157+
}
158+
}
159+
if (ex.InnerException != null)
160+
{
161+
string errorMessage = ex.InnerException.ErrorMessage;
162+
string errorType = ex.InnerException.ErrorType;
163+
if (errorMessage != null)
164+
{
165+
builder.Append(errorMessage.Trim());
166+
builder.Append(": ");
167+
}
168+
builder.AppendLine(errorType);
169+
AppendStackTraceToStringBuilder(builder, ex.InnerException);
170+
}
171+
}
172+
173+
internal static Lazy<CognitoClientContextInternal> GetCognitoClientContextInternalLazy(string text)
174+
{
175+
return new Lazy<CognitoClientContextInternal>(delegate
176+
{
177+
CognitoClientContextInternal result = null;
178+
if (!string.IsNullOrEmpty(text))
179+
{
180+
try
181+
{
182+
return CognitoClientContextInternal.FromJson(text);
183+
}
184+
catch (Exception innerException)
185+
{
186+
throw LambdaExceptions.ValidationException(innerException, "Unable to parse client context JSON string '{0}'.", text);
187+
}
188+
}
189+
return result;
190+
});
191+
}
192+
}
193+
194+
internal class MockXRayProfiler : IXRayProfiler
195+
{
196+
public void ReportUserInitStart()
197+
{
198+
}
199+
200+
public void ReportUserInitEnd()
201+
{
202+
}
203+
204+
public void ReportUserInvokeStart()
205+
{
206+
}
207+
208+
public void ReportUserInvokeEnd()
209+
{
210+
}
211+
212+
public void ReportError(ExceptionResponse exceptionResponse)
213+
{
214+
}
215+
}
216+
217+
}
Collapse file

‎dotnetcore2.1/run/MockBootstraps/Program.cs‎

Copy file name to clipboardExpand all lines: dotnetcore2.1/run/MockBootstraps/Program.cs
+8-59Lines changed: 8 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
using System;
22
using System.Collections.Generic;
33
using System.IO;
4+
using System.Linq;
45
using System.Reflection;
56
using System.Runtime.Loader;
67
using AWSLambda.Internal.Bootstrap;
7-
using AWSLambda.Internal.Bootstrap.Context;
8-
using System.Linq;
9-
8+
using AWSLambda.Internal.Bootstrap.ErrorHandling;
9+
1010
namespace MockLambdaRuntime
1111
{
1212
class Program
@@ -51,40 +51,11 @@ static void Main(string[] args)
5151
}
5252
}
5353

54-
var lambdaContext = new MockLambdaContext(handler, body);
55-
56-
var userCodeLoader = new UserCodeLoader(handler, InternalLogger.NO_OP_LOGGER);
57-
userCodeLoader.Init(Console.Error.WriteLine);
58-
59-
var lambdaContextInternal = new LambdaContextInternal(lambdaContext.RemainingTime,
60-
LogAction, new Lazy<CognitoClientContextInternal>(),
61-
lambdaContext.RequestId,
62-
new Lazy<string>(lambdaContext.Arn),
63-
new Lazy<string>(string.Empty),
64-
new Lazy<string>(string.Empty),
65-
Environment.GetEnvironmentVariables());
66-
67-
Exception lambdaException = null;
68-
69-
LogRequestStart(lambdaContext);
70-
try
71-
{
72-
userCodeLoader.Invoke(lambdaContext.InputStream, lambdaContext.OutputStream, lambdaContextInternal);
73-
}
74-
catch (Exception ex)
75-
{
76-
lambdaException = ex;
77-
}
78-
LogRequestEnd(lambdaContext);
79-
80-
if (lambdaException == null)
81-
{
82-
Console.WriteLine(lambdaContext.OutputText);
83-
}
84-
else
85-
{
86-
Console.Error.WriteLine(lambdaException);
87-
}
54+
var lambdaRuntime = new MockRuntime(handler, body);
55+
LambdaBootstrap lambdaBootstrap = new LambdaBootstrap(lambdaRuntime, InternalLogger.NO_OP_LOGGER);
56+
UnhandledExceptionLogger.Register();
57+
lambdaBootstrap.Initialize();
58+
lambdaBootstrap.Invoke();
8859
}
8960

9061
// Catch all unhandled exceptions from runtime, to prevent user from hanging on them while debugging
@@ -111,12 +82,6 @@ private static Assembly OnAssemblyResolving(AssemblyLoadContext context, Assembl
11182
throw new FileNotFoundException($"{assemblyName.Name}.dll");
11283
}
11384

114-
/// Try to log everything to stderr except the function result
115-
private static void LogAction(string text)
116-
{
117-
Console.Error.WriteLine(text);
118-
}
119-
12085
/// <summary>
12186
/// Extracts "waitForDebugger" flag from args. Returns other unprocessed arguments.
12287
/// </summary>
@@ -144,22 +109,6 @@ private static bool GetShouldWaitForDebuggerFlag(string[] args, out string[] unp
144109
return flagValue;
145110
}
146111

147-
static void LogRequestStart(MockLambdaContext context)
148-
{
149-
Console.Error.WriteLine($"START RequestId: {context.RequestId} Version: {context.FunctionVersion}");
150-
}
151-
152-
static void LogRequestEnd(MockLambdaContext context)
153-
{
154-
Console.Error.WriteLine($"END RequestId: {context.RequestId}");
155-
156-
Console.Error.WriteLine($"REPORT RequestId {context.RequestId}\t" +
157-
$"Duration: {context.Duration} ms\t" +
158-
$"Billed Duration: {context.BilledDuration} ms\t" +
159-
$"Memory Size {context.MemorySize} MB\t" +
160-
$"Max Memory Used: {context.MemoryUsed / (1024 * 1024)} MB");
161-
}
162-
163112
/// Gets the function handler from arguments or environment
164113
static string GetFunctionHandler(string[] args)
165114
{

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.