├── .gitignore ├── .travis.yml ├── Aliyun.Serverless.Core.Http ├── Aliyun.Serverless.Core.Http.csproj ├── FcHttpEntrypoint.cs ├── FcHttpServer.cs ├── FcWebHostBuilderExtensions.cs └── InvokeFeatures.cs ├── Aliyun.Serverless.Core.Mock ├── .DS_Store ├── Aliyun.Serverless.Core.Mock.csproj ├── ConsoleLogger.cs ├── Credentials.cs ├── FcContext.cs ├── FunctionParameter.cs └── ServiceMeta.cs ├── Aliyun.Serverless.Core ├── Aliyun.Serverless.Core.csproj ├── FcSerializerAttribute.cs ├── ICredentials.cs ├── IFcContext.cs ├── IFcLogger.cs ├── IFcSerializer.cs ├── IFunctionParameter.cs ├── IServiceMeta.cs └── JsonSerializerException.cs ├── Aliyun.Serverless.Events ├── Aliyun.Serverless.Events.csproj └── OSSEvent.cs ├── Aliyun.Serverless.sln ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .vs 3 | bin 4 | obj 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | solution: Aliyun.Serverless.sln 3 | 4 | mono: none 5 | 6 | dotnet: 2.1.4 7 | 8 | script: 9 | - dotnet build Aliyun.Serverless.sln 10 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Http/Aliyun.Serverless.Core.Http.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | Alibaba Cloud 6 | The SDK for developing http invoke functions of Alibaba Cloud Function Compute 7 | Aliyun.Serverless.Core.Http 8 | Aliyun;Alibaba Cloud;Serverless 9 | 1.0.3 10 | Aliyun Serverless .NET Core support - Core package. 11 | Aliyun.Serverless.Core.Http 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Http/FcHttpEntrypoint.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | 4 | using Microsoft.AspNetCore.Hosting; 5 | using Microsoft.AspNetCore.Hosting.Internal; 6 | using Microsoft.AspNetCore.Http.Features; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Logging; 10 | using Microsoft.Extensions.Primitives; 11 | using System.Collections.Generic; 12 | using System.IO; 13 | using System.Linq; 14 | using System.Net; 15 | using System.Reflection; 16 | using System.Security.Claims; 17 | using System.Text; 18 | using System.Text.Encodings.Web; 19 | using Microsoft.AspNetCore.Http; 20 | using Microsoft.Extensions.FileProviders; 21 | namespace Aliyun.Serverless.Core.Http 22 | { 23 | public abstract class FcHttpEntrypoint 24 | { 25 | /// 26 | /// Key to access the ILambdaContext object from the HttpContext.Items collection. 27 | /// 28 | public const string FC_CONTEXT = "FcContext"; 29 | 30 | private FcHttpServer _server; 31 | 32 | protected IWebHost _host; 33 | 34 | private static string _pathBase; 35 | 36 | private static readonly object startLock = new object(); 37 | 38 | /// 39 | /// Should be called in the derived constructor 40 | /// 41 | protected void Start() 42 | { 43 | var builder = CreateWebHostBuilder(); 44 | Init(builder); 45 | 46 | _host = builder.Build(); 47 | this.PostInit(_host); 48 | _host.Start(); 49 | 50 | _server = _host.Services.GetService(typeof(Microsoft.AspNetCore.Hosting.Server.IServer)) as FcHttpServer; 51 | if (_server == null) 52 | { 53 | throw new Exception("Failed to find the implementation FcHttpServer for the IServer registration. This can happen if UseFcServer was not called."); 54 | } 55 | } 56 | 57 | /// 58 | /// Gets the logger. 59 | /// 60 | /// The logger. 61 | public IFcLogger Logger { get; private set; } 62 | 63 | public static string PathBase 64 | { 65 | get 66 | { 67 | return _pathBase; 68 | } 69 | } 70 | 71 | public static string AppCodePath 72 | { 73 | get; set; 74 | } 75 | 76 | /// 77 | /// Gets a value indicating whether this is started. 78 | /// 79 | /// true if is started; otherwise, false. 80 | private bool IsStarted 81 | { 82 | get 83 | { 84 | return _server != null; 85 | } 86 | } 87 | 88 | /// 89 | /// Method to initialize the web builder before starting the web host. In a typical Web API this is similar to the main function. 90 | /// Setting the Startup class is required in this method. 91 | /// 92 | /// 93 | /// 94 | /// protected override void Init(IWebHostBuilder builder) 95 | /// { 96 | /// builder 97 | /// .UseStartup<Startup>(); 98 | /// } 99 | /// 100 | /// 101 | /// 102 | protected abstract void Init(IWebHostBuilder builder); 103 | 104 | /// 105 | /// action after init. 106 | /// 107 | /// Host. 108 | protected virtual void PostInit(IWebHost host) { } 109 | 110 | /// 111 | /// Creates the IWebHostBuilder similar to WebHost.CreateDefaultBuilder but replacing the registration of the Kestrel web server with a 112 | /// registration for ApiGateway. 113 | /// 114 | /// 115 | protected virtual IWebHostBuilder CreateWebHostBuilder() 116 | { 117 | var builder = new WebHostBuilder() 118 | .ConfigureAppConfiguration((hostingContext, config) => 119 | { 120 | var env = hostingContext.HostingEnvironment; 121 | 122 | config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 123 | .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); 124 | PhysicalFileProvider fileProvider = config.Properties["FileProvider"] as PhysicalFileProvider; 125 | if (fileProvider != null) 126 | { 127 | Logger.LogInformation("FileProvider Root: {0}", fileProvider.Root); 128 | } 129 | 130 | if (env.IsDevelopment()) 131 | { 132 | var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); 133 | if (appAssembly != null) 134 | { 135 | config.AddUserSecrets(appAssembly, optional: true); 136 | } 137 | } 138 | 139 | config.AddEnvironmentVariables(); 140 | }) 141 | .ConfigureLogging((hostingContext, logging) => 142 | { 143 | logging.ClearProviders(); 144 | }) 145 | .UseDefaultServiceProvider((hostingContext, options) => 146 | { 147 | options.ValidateScopes = hostingContext.HostingEnvironment.IsDevelopment(); 148 | }) 149 | .UseFcServer(); 150 | 151 | return builder; 152 | } 153 | 154 | public virtual async Task HandleRequest(HttpRequest request, HttpResponse response, IFcContext fcContext) 155 | { 156 | Logger = fcContext.Logger; 157 | lock (startLock) 158 | { 159 | if (!IsStarted) 160 | { 161 | _pathBase = request.PathBase; 162 | Logger.LogInformation("Setting global PathBase {0}", _pathBase); 163 | Start(); 164 | } 165 | } 166 | 167 | Logger.LogDebug("Incoming {0} requests Path: {1}, Pathbase {2}", request.Method, request.Path, request.PathBase); 168 | 169 | InvokeFeatures features = new InvokeFeatures(); 170 | MarshallRequest(features, request, fcContext); 171 | Logger.LogDebug($"ASP.NET Core Request PathBase: {((IHttpRequestFeature)features).PathBase}, Path: {((IHttpRequestFeature)features).Path}"); 172 | 173 | var httpContext = this.CreateContext(features); 174 | 175 | if (request?.HttpContext?.User != null) 176 | { 177 | httpContext.HttpContext.User = request.HttpContext.User; 178 | } 179 | 180 | // Add along the Lambda objects to the HttpContext to give access to FC to them in the ASP.NET Core application 181 | httpContext.HttpContext.Items[FC_CONTEXT] = fcContext; 182 | 183 | // Allow the context to be customized before passing the request to ASP.NET Core. 184 | PostCreateContext(httpContext, request, fcContext); 185 | 186 | await this.ProcessRequest(fcContext, httpContext, features, response); 187 | 188 | return response; 189 | } 190 | 191 | /// 192 | /// This method is called after the FcHttpEntrypoint has marshalled the incoming API request 193 | /// into ASP.NET Core's IHttpRequestFeature. Derived classes can overwrite this method to alter 194 | /// the how the marshalling was done. 195 | /// 196 | /// ASP net core request feature. 197 | /// Request. 198 | /// Fc context. 199 | protected virtual void PostMarshallRequestFeature(IHttpRequestFeature aspNetCoreRequestFeature, HttpRequest request, IFcContext fcContext) 200 | { 201 | 202 | } 203 | 204 | 205 | /// 206 | /// This method is called after the FcHttpEntrypoint has marshalled the incoming API Gateway request 207 | /// into ASP.NET Core's IHttpConnectionFeature. Derived classes can overwrite this method to alter 208 | /// the how the marshalling was done. 209 | /// 210 | /// ASP net core connection feature. 211 | /// Request. 212 | /// Fc context. 213 | protected virtual void PostMarshallConnectionFeature(IHttpConnectionFeature aspNetCoreConnectionFeature, HttpRequest request, IFcContext fcContext) 214 | { 215 | 216 | } 217 | 218 | 219 | /// 220 | /// This method is called after the FcHttpEntrypoint has marshalled IHttpResponseFeature that came 221 | /// back from making the request into ASP.NET Core into API Gateway's response object HttpResonse. Derived classes can overwrite this method to alter 222 | /// the how the marshalling was done. 223 | /// 224 | /// ASP net core response feature. 225 | /// Response. 226 | /// Fc context. 227 | protected virtual void PostMarshallResponseFeature(IHttpResponseFeature aspNetCoreResponseFeature, HttpResponse response, IFcContext fcContext) 228 | { 229 | 230 | } 231 | 232 | 233 | /// 234 | /// This method is called after the HostingApplication.Context has been created. Derived classes can overwrite this method to alter 235 | /// the context before passing the request to ASP.NET Core to process the request. 236 | /// 237 | /// Context. 238 | /// Request. 239 | /// Fc context. 240 | protected virtual void PostCreateContext(HostingApplication.Context context, HttpRequest request, IFcContext fcContext) 241 | { 242 | 243 | } 244 | 245 | /// 246 | /// Creates a object using the field in the class. 247 | /// 248 | /// implementation. 249 | protected HostingApplication.Context CreateContext(IFeatureCollection features) 250 | { 251 | return _server.Application.CreateContext(features); 252 | } 253 | 254 | /// 255 | /// Convert the JSON document received from API Gateway into the InvokeFeatures object. 256 | /// InvokeFeatures is then passed into IHttpApplication to create the ASP.NET Core request objects. 257 | /// 258 | /// Features. 259 | /// Request. 260 | /// Fc context. 261 | protected void MarshallRequest(InvokeFeatures features, HttpRequest request, IFcContext fcContext) 262 | { 263 | { 264 | var requestFeatures = (IHttpRequestFeature)features; 265 | requestFeatures.Scheme = "https"; 266 | requestFeatures.Method = request.Method; 267 | 268 | requestFeatures.Path = request.Path; // the PathString ensures it starts with "/"; 269 | requestFeatures.PathBase = request.PathBase; 270 | requestFeatures.QueryString = request.QueryString.Value; 271 | requestFeatures.Headers = request.Headers; 272 | requestFeatures.Body = request.Body; 273 | 274 | // Call consumers customize method in case they want to change how API request 275 | // was marshalled into ASP.NET Core request. 276 | PostMarshallRequestFeature(requestFeatures, request, fcContext); 277 | } 278 | 279 | 280 | { 281 | // set up connection features 282 | var connectionFeatures = (IHttpConnectionFeature)features; 283 | connectionFeatures.RemoteIpAddress = request?.HttpContext?.Connection?.RemoteIpAddress; 284 | if (request?.HttpContext?.Connection?.RemotePort != null) 285 | { 286 | connectionFeatures.RemotePort = (request?.HttpContext?.Connection?.RemotePort).Value; 287 | } 288 | 289 | if (request?.Headers?.ContainsKey("X-Forwarded-Port") == true) 290 | { 291 | connectionFeatures.RemotePort = int.Parse(request.Headers["X-Forwarded-Port"]); 292 | } 293 | 294 | // Call consumers customize method in case they want to change how API Gateway's request 295 | // was marshalled into ASP.NET Core request. 296 | PostMarshallConnectionFeature(connectionFeatures, request, fcContext); 297 | } 298 | } 299 | 300 | /// 301 | /// Convert the response coming from ASP.NET Core into APIGatewayProxyResponse which is 302 | /// serialized into the JSON object that API Gateway expects. 303 | /// 304 | /// The response. 305 | /// Response features. 306 | /// Fc context. 307 | /// Status code if not set. 308 | protected HttpResponse MarshallResponse(IHttpResponseFeature responseFeatures, IFcContext fcContext, HttpResponse response, int statusCodeIfNotSet = 200) 309 | { 310 | response.StatusCode = responseFeatures.StatusCode != 0 ? responseFeatures.StatusCode : statusCodeIfNotSet; 311 | string contentType = null; 312 | if (responseFeatures.Headers != null) 313 | { 314 | foreach (var kvp in responseFeatures.Headers) 315 | { 316 | response.Headers[kvp.Key] = kvp.Value; 317 | 318 | // Remember the Content-Type for possible later use 319 | if (kvp.Key.Equals("Content-Type", StringComparison.CurrentCultureIgnoreCase)) 320 | contentType = response.Headers[kvp.Key]; 321 | } 322 | } 323 | 324 | if (contentType == null) 325 | { 326 | response.Headers["Content-Type"] = StringValues.Empty; 327 | } 328 | 329 | response.Body = responseFeatures.Body; 330 | 331 | PostMarshallResponseFeature(responseFeatures, response, fcContext); 332 | 333 | return response; 334 | } 335 | 336 | /// 337 | /// Processes the current request. 338 | /// 339 | /// implementation. 340 | /// The hosting application request context object. 341 | /// An instance. 342 | /// 343 | /// If specified, an unhandled exception will be rethrown for custom error handling. 344 | /// Ensure that the error handling code calls 'this.MarshallResponse(features, 500);' after handling the error to return a to the user. 345 | /// 346 | protected async Task ProcessRequest(IFcContext fcContext, HostingApplication.Context context, InvokeFeatures features, HttpResponse response, bool rethrowUnhandledError = false) 347 | { 348 | var defaultStatusCode = 200; 349 | Exception ex = null; 350 | try 351 | { 352 | await this._server.Application.ProcessRequestAsync(context); 353 | } 354 | catch (AggregateException agex) 355 | { 356 | ex = agex; 357 | Logger.LogError($"Caught AggregateException: '{agex}'"); 358 | var sb = new StringBuilder(); 359 | foreach (var newEx in agex.InnerExceptions) 360 | { 361 | sb.AppendLine(this.ErrorReport(newEx)); 362 | } 363 | 364 | Logger.LogError(sb.ToString()); 365 | defaultStatusCode = 500; 366 | } 367 | catch (ReflectionTypeLoadException rex) 368 | { 369 | ex = rex; 370 | Logger.LogError($"Caught ReflectionTypeLoadException: '{rex}'"); 371 | var sb = new StringBuilder(); 372 | foreach (var loaderException in rex.LoaderExceptions) 373 | { 374 | var fileNotFoundException = loaderException as FileNotFoundException; 375 | if (fileNotFoundException != null && !string.IsNullOrEmpty(fileNotFoundException.FileName)) 376 | { 377 | sb.AppendLine($"Missing file: {fileNotFoundException.FileName}"); 378 | } 379 | else 380 | { 381 | sb.AppendLine(this.ErrorReport(loaderException)); 382 | } 383 | } 384 | 385 | Logger.LogError(sb.ToString()); 386 | defaultStatusCode = 500; 387 | } 388 | catch (Exception e) 389 | { 390 | ex = e; 391 | if (rethrowUnhandledError) throw; 392 | Logger.LogError($"Unknown error responding to request: {this.ErrorReport(e)}"); 393 | defaultStatusCode = 500; 394 | } 395 | finally 396 | { 397 | this._server.Application.DisposeContext(context, ex); 398 | } 399 | 400 | if (features.ResponseStartingEvents != null) 401 | { 402 | await features.ResponseStartingEvents.ExecuteAsync(); 403 | } 404 | 405 | this.MarshallResponse(features, fcContext, response, defaultStatusCode); 406 | 407 | if (features.ResponseCompletedEvents != null) 408 | { 409 | await features.ResponseCompletedEvents.ExecuteAsync(); 410 | } 411 | 412 | return response; 413 | } 414 | 415 | /// 416 | /// Formats an Exception into a string, including all inner exceptions. 417 | /// 418 | /// instance. 419 | protected string ErrorReport(Exception e) 420 | { 421 | var sb = new StringBuilder(); 422 | sb.AppendLine($"{e.GetType().Name}:\n{e}"); 423 | 424 | Exception inner = e; 425 | while (inner != null) 426 | { 427 | // Append the messages to the StringBuilder. 428 | sb.AppendLine($"{inner.GetType().Name}:\n{inner}"); 429 | inner = inner.InnerException; 430 | } 431 | 432 | return sb.ToString(); 433 | } 434 | } 435 | } 436 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Http/FcHttpServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Microsoft.AspNetCore.Hosting.Internal; 5 | using Microsoft.AspNetCore.Hosting.Server; 6 | using Microsoft.AspNetCore.Http.Features; 7 | 8 | namespace Aliyun.Serverless.Core.Http 9 | { 10 | public class FcHttpServer : IServer 11 | { 12 | /// 13 | /// The application is used by the Fc function to initiate a web request through the ASP.NET Core framework. 14 | /// 15 | public IHttpApplication Application { get; set; } 16 | 17 | /// 18 | /// Gets the features. 19 | /// 20 | /// The features. 21 | public IFeatureCollection Features { get; } = new FeatureCollection(); 22 | 23 | public void Dispose() 24 | { 25 | } 26 | 27 | public Task StartAsync(IHttpApplication application, CancellationToken cancellationToken) 28 | { 29 | this.Application = application as IHttpApplication; 30 | return Task.CompletedTask; 31 | } 32 | 33 | public Task StopAsync(CancellationToken cancellationToken) 34 | { 35 | return Task.CompletedTask; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Http/FcWebHostBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.AspNetCore.Hosting.Server; 8 | using Aliyun.Serverless.Core.Http; 9 | 10 | namespace Microsoft.AspNetCore.Hosting 11 | { 12 | public static class FcWebHostBuilderExtensions 13 | { 14 | public static IWebHostBuilder UseFcServer(this IWebHostBuilder builder) 15 | { 16 | return builder.ConfigureServices(services => 17 | { 18 | var serviceDescription = services.FirstOrDefault(x => x.ServiceType == typeof(IServer)); 19 | if (serviceDescription != null) 20 | { 21 | // If Fc server has already been added the skip out. 22 | if (serviceDescription.ImplementationType == typeof(FcHttpServer)) 23 | return; 24 | // If there is already an IServer registered then remove it. This is mostly likely caused 25 | // by leaving the UseKestrel call. 26 | else 27 | services.Remove(serviceDescription); 28 | } 29 | 30 | services.AddSingleton(); 31 | }); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Http/InvokeFeatures.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Threading.Tasks; 8 | 9 | using Microsoft.AspNetCore.Http; 10 | using Microsoft.AspNetCore.Http.Features; 11 | 12 | #pragma warning disable 1591 13 | 14 | namespace Aliyun.Serverless.Core.Http 15 | { 16 | public class InvokeFeatures : IFeatureCollection, 17 | IHttpRequestFeature, 18 | IHttpResponseFeature, 19 | IHttpConnectionFeature 20 | { 21 | 22 | public InvokeFeatures() 23 | { 24 | _features[typeof(IHttpRequestFeature)] = this; 25 | _features[typeof(IHttpResponseFeature)] = this; 26 | _features[typeof(IHttpConnectionFeature)] = this; 27 | } 28 | 29 | #region IFeatureCollection 30 | public bool IsReadOnly => false; 31 | 32 | IDictionary _features = new Dictionary(); 33 | 34 | public int Revision => 0; 35 | 36 | public object this[Type key] 37 | { 38 | get 39 | { 40 | object feature; 41 | if (_features.TryGetValue(key, out feature)) 42 | { 43 | return feature; 44 | } 45 | 46 | return null; 47 | } 48 | 49 | set 50 | { 51 | _features[key] = value; 52 | } 53 | } 54 | 55 | public TFeature Get() 56 | { 57 | object feature; 58 | if (_features.TryGetValue(typeof(TFeature), out feature)) 59 | { 60 | return (TFeature)feature; 61 | } 62 | 63 | return default(TFeature); 64 | } 65 | 66 | public IEnumerator> GetEnumerator() 67 | { 68 | return this._features.GetEnumerator(); 69 | } 70 | 71 | public void Set(TFeature instance) 72 | { 73 | if (instance == null) 74 | return; 75 | 76 | this._features[typeof(TFeature)] = instance; 77 | } 78 | 79 | IEnumerator IEnumerable.GetEnumerator() 80 | { 81 | return this._features.GetEnumerator(); 82 | } 83 | 84 | #endregion 85 | 86 | #region IHttpRequestFeature 87 | string IHttpRequestFeature.Protocol { get; set; } 88 | 89 | string IHttpRequestFeature.Scheme { get; set; } 90 | 91 | string IHttpRequestFeature.Method { get; set; } 92 | 93 | string IHttpRequestFeature.PathBase { get; set; } 94 | 95 | string IHttpRequestFeature.Path { get; set; } 96 | 97 | string IHttpRequestFeature.QueryString { get; set; } 98 | 99 | string IHttpRequestFeature.RawTarget { get; set; } 100 | 101 | IHeaderDictionary IHttpRequestFeature.Headers { get; set; } = new HeaderDictionary(); 102 | 103 | Stream IHttpRequestFeature.Body { get; set; } = new MemoryStream(); 104 | 105 | #endregion 106 | 107 | #region IHttpResponseFeature 108 | int IHttpResponseFeature.StatusCode 109 | { 110 | get; 111 | set; 112 | } 113 | 114 | string IHttpResponseFeature.ReasonPhrase 115 | { 116 | get; 117 | set; 118 | } 119 | 120 | bool IHttpResponseFeature.HasStarted 121 | { 122 | get; 123 | } 124 | 125 | IHeaderDictionary IHttpResponseFeature.Headers 126 | { 127 | get; 128 | set; 129 | } = new HeaderDictionary(); 130 | 131 | Stream IHttpResponseFeature.Body 132 | { 133 | get; 134 | set; 135 | } = new MemoryStream(); 136 | 137 | internal EventCallbacks ResponseStartingEvents { get; private set; } 138 | void IHttpResponseFeature.OnStarting(Func callback, object state) 139 | { 140 | if (ResponseStartingEvents == null) 141 | this.ResponseStartingEvents = new EventCallbacks(); 142 | 143 | this.ResponseStartingEvents.Add(callback, state); 144 | } 145 | 146 | internal EventCallbacks ResponseCompletedEvents { get; private set; } 147 | void IHttpResponseFeature.OnCompleted(Func callback, object state) 148 | { 149 | if (this.ResponseCompletedEvents == null) 150 | this.ResponseCompletedEvents = new EventCallbacks(); 151 | 152 | this.ResponseCompletedEvents.Add(callback, state); 153 | } 154 | 155 | internal class EventCallbacks 156 | { 157 | List _callbacks = new List(); 158 | 159 | internal void Add(Func callback, object state) 160 | { 161 | this._callbacks.Add(new EventCallback(callback, state)); 162 | } 163 | 164 | internal async Task ExecuteAsync() 165 | { 166 | foreach (var callback in _callbacks) 167 | { 168 | await callback.ExecuteAsync(); 169 | } 170 | } 171 | 172 | internal class EventCallback 173 | { 174 | internal EventCallback(Func callback, object state) 175 | { 176 | this.Callback = callback; 177 | this.State = state; 178 | } 179 | 180 | Func Callback { get; } 181 | object State { get; } 182 | 183 | internal Task ExecuteAsync() 184 | { 185 | var task = Callback(this.State); 186 | return task; 187 | } 188 | } 189 | } 190 | 191 | #endregion 192 | 193 | #region IHttpConnectionFeature 194 | 195 | string IHttpConnectionFeature.ConnectionId { get; set; } 196 | 197 | IPAddress IHttpConnectionFeature.RemoteIpAddress { get; set; } 198 | 199 | IPAddress IHttpConnectionFeature.LocalIpAddress { get; set; } 200 | 201 | int IHttpConnectionFeature.RemotePort { get; set; } 202 | 203 | int IHttpConnectionFeature.LocalPort { get; set; } 204 | 205 | #endregion 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Mock/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aliyun/fc-dotnet-libs/7d7d5b3fb14764b8a414ed33f14ceb6fdc51d057/Aliyun.Serverless.Core.Mock/.DS_Store -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Mock/Aliyun.Serverless.Core.Mock.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | Aliyun.Serverless.Core.Mock 6 | 1.0.1 7 | The mock implementation for Aliyun.Serverless.Core's interfaces for local test purpose 8 | Alibaba Cloud 9 | The SDK for developing functions of Alibaba Cloud Function Compute 10 | Aliyun.Serverless.Core.Mock 11 | Aliyun;Alibaba Cloud;Serverless 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Mock/ConsoleLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Aliyun.Serverless.Core; 3 | using Microsoft.Extensions.Logging; 4 | namespace Aliyun.Serverless.Core.Mock 5 | { 6 | public class ConsoleLogger : IFcLogger 7 | { 8 | public ConsoleLogger(LogLevel logLevel) 9 | { 10 | EnabledLogLevel = logLevel; 11 | } 12 | 13 | /// 14 | /// Gets or sets the request Id. 15 | /// 16 | /// The prefix. 17 | public string RequestId 18 | { 19 | get; 20 | set; 21 | } 22 | 23 | /// 24 | /// Gets or sets the enabled log level. 25 | /// 26 | /// The enabled log level. 27 | public LogLevel EnabledLogLevel 28 | { 29 | get; 30 | set; 31 | } 32 | 33 | /// 34 | /// Writes a log entry. 35 | /// 36 | /// Entry will be written on this level. 37 | /// Id of the event. 38 | /// The entry to be written. Can be also an object. 39 | /// The exception related to this entry. 40 | /// Function to create a string message of the and . 41 | public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) 42 | { 43 | if (IsEnabled(logLevel)) 44 | { 45 | string s = formatter(state, exception); 46 | Console.WriteLine(string.Format("{0} {1} [{2}] {3}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"), RequestId, ToFcLogLevel(logLevel), s)); 47 | } 48 | } 49 | 50 | /// 51 | /// Checks if the given is enabled. 52 | /// 53 | /// level to be checked. 54 | /// true if enabled. 55 | public bool IsEnabled(LogLevel logLevel) 56 | { 57 | return logLevel >= EnabledLogLevel; 58 | } 59 | 60 | public IDisposable BeginScope(TState state) 61 | { 62 | return null; 63 | } 64 | 65 | /// 66 | /// convert LogLevel to the fc log level. 67 | /// 68 | /// The fc log level. 69 | /// Log level. 70 | public static string ToFcLogLevel(LogLevel logLevel) 71 | { 72 | switch (logLevel) 73 | { 74 | case LogLevel.Information: 75 | return "INFO"; 76 | case LogLevel.Trace: 77 | return "TRACE"; 78 | case LogLevel.Debug: 79 | return "DEBUG"; 80 | case LogLevel.Warning: 81 | return "WARNING"; 82 | case LogLevel.Error: 83 | case LogLevel.Critical: 84 | return "ERROR"; 85 | } 86 | 87 | return "UNKNOWN"; 88 | } 89 | 90 | /// 91 | /// Tos the log level. 92 | /// 93 | /// The log level. 94 | /// Fc log level. 95 | public static LogLevel ToLogLevel(string fcLogLevel) 96 | { 97 | if (fcLogLevel == null) 98 | { 99 | return LogLevel.Information; 100 | } 101 | 102 | switch (fcLogLevel.ToUpper()) 103 | { 104 | case "INFO": 105 | return LogLevel.Information; 106 | case "TRACE": 107 | return LogLevel.Trace; 108 | case "DEBUG": 109 | return LogLevel.Debug; 110 | case "WARNING": 111 | return LogLevel.Warning; 112 | case "ERROR": 113 | return LogLevel.Error; 114 | default: 115 | break; 116 | } 117 | 118 | return LogLevel.Information; // default 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Mock/Credentials.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Aliyun.Serverless.Core; 3 | namespace Aliyun.Serverless.Core.Mock 4 | { 5 | public class Credentials : ICredentials 6 | { 7 | /// 8 | /// Gets the access key identifier. 9 | /// 10 | /// The access key identifier. 11 | public string AccessKeyId { get; set; } 12 | 13 | /// 14 | /// Gets the access key secret. 15 | /// 16 | /// The access key secret. 17 | public string AccessKeySecret { get; set; } 18 | 19 | /// 20 | /// Gets the security token. 21 | /// 22 | /// The security token. 23 | public string SecurityToken { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Mock/FcContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Aliyun.Serverless.Core; 3 | 4 | namespace Aliyun.Serverless.Core.Mock 5 | { 6 | public class FcContext : IFcContext 7 | { 8 | private FunctionParameter _functionParam = new FunctionParameter(); 9 | private ConsoleLogger _logger = new ConsoleLogger(Microsoft.Extensions.Logging.LogLevel.Information); 10 | private ICredentials _credentials = new Credentials(); 11 | private ServiceMeta _meta = new ServiceMeta(); 12 | public FcContext(string accountId, string reqId) 13 | { 14 | AccountId = accountId; 15 | this.RequestId = reqId; 16 | } 17 | 18 | /// 19 | /// The AliFc request ID associated with the request. 20 | /// This is the same ID returned to the client that called invoke(). 21 | /// This ID is reused for retries on the same request. 22 | /// 23 | public string RequestId { get; set; } 24 | 25 | /// 26 | /// Gets the function parameter interface. 27 | /// 28 | /// The function parameter interface. 29 | public IFunctionParameter FunctionParam { get { return _functionParam; } } 30 | 31 | /// 32 | /// AliFc logger associated with the Context object. 33 | /// 34 | public IFcLogger Logger { get { return _logger; } } 35 | 36 | /// 37 | /// Gets the credentials interface. 38 | /// 39 | /// The credentials interface. 40 | public ICredentials Credentials { get { return _credentials; } set { _credentials = value; } } 41 | 42 | /// 43 | /// Gets the account identifier. 44 | /// 45 | /// The account identifier. 46 | public string AccountId { get; set; } 47 | 48 | /// 49 | /// Gets the region. 50 | /// 51 | /// The region. 52 | public string Region { get; } 53 | 54 | /// 55 | /// Gets the service meta. 56 | /// 57 | /// The service meta. 58 | public IServiceMeta ServiceMeta { get { return _meta; } } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Mock/FunctionParameter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Aliyun.Serverless.Core; 3 | namespace Aliyun.Serverless.Core.Mock 4 | { 5 | public class FunctionParameter : IFunctionParameter 6 | { 7 | /// 8 | /// Gets the name of the function. 9 | /// 10 | /// The name of the function. 11 | public string FunctionName { get; set; } 12 | 13 | /// 14 | /// Gets the function handler. 15 | /// 16 | /// The function handler. 17 | public string FunctionHandler { get; set; } 18 | 19 | 20 | /// 21 | /// Gets the initializer. 22 | /// 23 | /// The initializer. 24 | public string FunctionInitializer { get; set; } 25 | 26 | /// 27 | /// Memory limit, in MB, you configured for the AliFc function. 28 | /// 29 | public int MemoryLimitInMB { get; set; } 30 | 31 | /// 32 | /// Remaining execution time till the function will be terminated. 33 | /// At the time you create the AliFc function you set maximum time 34 | /// limit, at which time AliFc will terminate the function 35 | /// execution. 36 | /// Information about the remaining time of function execution can be 37 | /// used to specify function behavior when nearing the timeout. 38 | /// 39 | public TimeSpan FunctionTimeout { get; set; } 40 | 41 | /// 42 | /// Gets the initializer timeout. 43 | /// 44 | /// The initializer timeout. 45 | public TimeSpan InitializationTimeout { get; set; } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core.Mock/ServiceMeta.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace Aliyun.Serverless.Core.Mock 3 | { 4 | public class ServiceMeta : IServiceMeta 5 | { 6 | /// 7 | /// Gets the name. 8 | /// 9 | /// The name. 10 | public string Name { get; set; } 11 | 12 | /// 13 | /// Gets the log project. 14 | /// 15 | /// The log project. 16 | public string LogProject { get; set; } 17 | 18 | /// 19 | /// Gets the log store. 20 | /// 21 | /// The log store. 22 | public string LogStore { get; set; } 23 | 24 | /// 25 | /// Gets the qualifier. 26 | /// 27 | /// The qualifier. 28 | public string Qualifier { get; set; } 29 | 30 | /// 31 | /// Gets the version identifier. 32 | /// 33 | /// The version identifier. 34 | public string VersionId { get; set; } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core/Aliyun.Serverless.Core.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | false 5 | 6 | Aliyun Serverless function computing 7 | 8 | Library 9 | true 10 | 11 | true 12 | 13 | false 14 | false 15 | false 16 | false 17 | false 18 | false 19 | false 20 | 21 | 22 | 23 | 24 | netstandard2.0 25 | 2.0.0 26 | Aliyun Serverless .NET Core support - Core package. 27 | Aliyun.Serverless.Core 28 | 1.0.0 29 | Aliyun.Serverless.Core 30 | Aliyun.Serverless.Core 31 | Aliyun;Alibaba Cloud;Serverless 32 | true 33 | 1.0.1 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core/FcSerializerAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace Aliyun.Serverless.Core 2 | { 3 | using System; 4 | 5 | /// 6 | /// This attribute is required for serialization of input/output parameters of 7 | /// a AliFc function if your AliFc function uses types other than string or 8 | /// System.IO.Stream as input/output parameters. 9 | /// 10 | /// This attribute can be applied to a method (serializer used for method input 11 | /// and output), or to an assembly (serializer used for all methods). 12 | /// 13 | [AttributeUsage(AttributeTargets.Method | AttributeTargets.Assembly, AllowMultiple = false)] 14 | public sealed class FcSerializerAttribute : System.Attribute 15 | { 16 | /// 17 | /// Type of the serializer. 18 | /// The custom serializer must implement Aliyun.Serverless.IAliFcSerializer 19 | /// interface, or an exception will be thrown. 20 | /// 21 | public Type SerializerType { get; set; } 22 | 23 | /// 24 | /// Constructs attribute with a specific serializer type. 25 | /// 26 | /// 27 | public FcSerializerAttribute(Type serializerType) 28 | { 29 | this.SerializerType = serializerType; 30 | } 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /Aliyun.Serverless.Core/ICredentials.cs: -------------------------------------------------------------------------------- 1 | namespace Aliyun.Serverless.Core 2 | { 3 | /// 4 | /// Credentials interface 5 | /// 6 | public interface ICredentials 7 | { 8 | /// 9 | /// Gets the access key identifier. 10 | /// 11 | /// The access key identifier. 12 | string AccessKeyId {get;} 13 | 14 | /// 15 | /// Gets the access key secret. 16 | /// 17 | /// The access key secret. 18 | string AccessKeySecret {get;} 19 | 20 | /// 21 | /// Gets the security token. 22 | /// 23 | /// The security token. 24 | string SecurityToken {get;} 25 | } 26 | } -------------------------------------------------------------------------------- /Aliyun.Serverless.Core/IFcContext.cs: -------------------------------------------------------------------------------- 1 | namespace Aliyun.Serverless.Core 2 | { 3 | using System; 4 | using Microsoft.Extensions.Logging; 5 | /// 6 | /// Object that allows you to access useful information available within 7 | /// the AliFc execution environment. 8 | /// 9 | public interface IFcContext 10 | { 11 | /// 12 | /// The AliFc request ID associated with the request. 13 | /// This is the same ID returned to the client that called invoke(). 14 | /// This ID is reused for retries on the same request. 15 | /// 16 | string RequestId { get; } 17 | 18 | /// 19 | /// Gets the function parameter interface. 20 | /// 21 | /// The function parameter interface. 22 | IFunctionParameter FunctionParam {get;} 23 | 24 | /// 25 | /// AliFc logger associated with the Context object. 26 | /// 27 | IFcLogger Logger { get; } 28 | 29 | /// 30 | /// Gets the credentials interface. 31 | /// 32 | /// The credentials interface. 33 | ICredentials Credentials {get;} 34 | 35 | /// 36 | /// Gets the account identifier. 37 | /// 38 | /// The account identifier. 39 | string AccountId { get; } 40 | 41 | /// 42 | /// Gets the region. 43 | /// 44 | /// The region. 45 | string Region { get; } 46 | 47 | /// 48 | /// Gets the service meta. 49 | /// 50 | /// The service meta. 51 | IServiceMeta ServiceMeta { get; } 52 | } 53 | } -------------------------------------------------------------------------------- /Aliyun.Serverless.Core/IFcLogger.cs: -------------------------------------------------------------------------------- 1 | namespace Aliyun.Serverless.Core 2 | { 3 | using Microsoft.Extensions.Logging; 4 | 5 | /// 6 | /// AliFc runtime logger. 7 | /// 8 | public interface IFcLogger : ILogger 9 | { 10 | /// 11 | /// Gets or sets the minimal log level that is enabled. 12 | /// 13 | /// The minimal log level. 14 | LogLevel EnabledLogLevel { get; set;} 15 | } 16 | } -------------------------------------------------------------------------------- /Aliyun.Serverless.Core/IFcSerializer.cs: -------------------------------------------------------------------------------- 1 | namespace Aliyun.Serverless.Core 2 | { 3 | using System.IO; 4 | 5 | /// 6 | /// Interface that must be implemented by custom serializers that 7 | /// may need to be called during execution. 8 | /// 9 | public interface IFcSerializer 10 | { 11 | /// 12 | /// This method is called to deserialize the request payload from Invoke API 13 | /// into the object that is passed to the AliFc function handler. 14 | /// 15 | /// Type of object to deserialize to. 16 | /// Stream to serialize. 17 | /// Deserialized object from stream. 18 | T Deserialize(Stream requestStream); 19 | 20 | /// 21 | /// This method is called to serialize the result returned from 22 | /// a AliFc function handler into the response payload 23 | /// that is returned by the Invoke API. 24 | /// 25 | /// Type of object to serialize. 26 | /// Object to serialize. 27 | /// Output stream. 28 | void Serialize(T response, Stream responseStream); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core/IFunctionParameter.cs: -------------------------------------------------------------------------------- 1 | namespace Aliyun.Serverless.Core 2 | { 3 | using System; 4 | 5 | /// 6 | /// Function parameter. 7 | /// 8 | public interface IFunctionParameter 9 | { 10 | /// 11 | /// Gets the name of the function. 12 | /// 13 | /// The name of the function. 14 | string FunctionName {get;} 15 | 16 | /// 17 | /// Gets the function handler. 18 | /// 19 | /// The function handler. 20 | string FunctionHandler {get;} 21 | 22 | 23 | /// 24 | /// Gets the initializer. 25 | /// 26 | /// The initializer. 27 | string FunctionInitializer { get; } 28 | 29 | /// 30 | /// Memory limit, in MB, you configured for the AliFc function. 31 | /// 32 | int MemoryLimitInMB { get; } 33 | 34 | /// 35 | /// Remaining execution time till the function will be terminated. 36 | /// At the time you create the AliFc function you set maximum time 37 | /// limit, at which time AliFc will terminate the function 38 | /// execution. 39 | /// Information about the remaining time of function execution can be 40 | /// used to specify function behavior when nearing the timeout. 41 | /// 42 | TimeSpan FunctionTimeout { get; } 43 | 44 | /// 45 | /// Gets the initializer timeout. 46 | /// 47 | /// The initializer timeout. 48 | TimeSpan InitializationTimeout { get; } 49 | } 50 | } -------------------------------------------------------------------------------- /Aliyun.Serverless.Core/IServiceMeta.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace Aliyun.Serverless.Core 3 | { 4 | /// 5 | /// Service meta. 6 | /// 7 | public interface IServiceMeta 8 | { 9 | /// 10 | /// Gets the name. 11 | /// 12 | /// The name. 13 | string Name { get; } 14 | 15 | /// 16 | /// Gets the log project. 17 | /// 18 | /// The log project. 19 | string LogProject { get; } 20 | 21 | /// 22 | /// Gets the log store. 23 | /// 24 | /// The log store. 25 | string LogStore { get; } 26 | 27 | /// 28 | /// Gets the qualifier. 29 | /// 30 | /// The qualifier. 31 | string Qualifier { get; } 32 | 33 | /// 34 | /// Gets the version identifier. 35 | /// 36 | /// The version identifier. 37 | string VersionId { get; } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Core/JsonSerializerException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Aliyun.Serverless.Core 4 | { 5 | /// 6 | /// Exception thrown when errors occur serializing and deserializng JSON documents from the AliFc service 7 | /// 8 | public class JsonSerializerException : Exception 9 | { 10 | /// 11 | /// Constructs instances of JsonSerializerException 12 | /// 13 | /// Exception message 14 | /// Inner exception for the JsonSerializerException 15 | public JsonSerializerException(string message, Exception exception) : base(message, exception) { } 16 | } 17 | } -------------------------------------------------------------------------------- /Aliyun.Serverless.Events/Aliyun.Serverless.Events.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Aliyun.Serverless.Events/OSSEvent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Newtonsoft.Json; 3 | 4 | namespace Aliyun.Serverless.Events 5 | { 6 | public class OSSEvent 7 | { 8 | public class Bucket 9 | { 10 | 11 | public readonly string arn; 12 | public readonly string name; 13 | public readonly string ownerIdentity; 14 | public readonly string virtualBucket; 15 | 16 | [JsonConstructor] 17 | public Bucket(string arn, 18 | string name, 19 | string ownerIdentity, 20 | string virtualBucket) 21 | { 22 | this.arn = arn; 23 | this.name = name; 24 | this.ownerIdentity = ownerIdentity; 25 | this.virtualBucket = virtualBucket; 26 | } 27 | } 28 | 29 | public class Object 30 | { 31 | public readonly long deltaSize; 32 | public readonly string eTag; 33 | public readonly string key; 34 | public readonly long size; 35 | 36 | [JsonConstructor] 37 | public Object(long deltaSize, 38 | string eTag, 39 | string key, 40 | long size) 41 | { 42 | this.deltaSize = deltaSize; 43 | this.eTag = eTag; 44 | this.key = key; 45 | this.size = size; 46 | } 47 | } 48 | 49 | public class RequestParameters 50 | { 51 | 52 | public readonly string sourceIPAddress; 53 | 54 | [JsonConstructor] 55 | public RequestParameters(string sourceIPAddress) 56 | { 57 | this.sourceIPAddress = sourceIPAddress; 58 | } 59 | } 60 | 61 | public class ResponseElements 62 | { 63 | public readonly string requestId; 64 | 65 | [JsonConstructor] 66 | public ResponseElements(string requestId) 67 | { 68 | this.requestId = requestId; 69 | } 70 | } 71 | 72 | public class UserIdentity 73 | { 74 | 75 | public readonly string principalId; 76 | 77 | [JsonConstructor] 78 | public UserIdentity(string principalId) 79 | { 80 | this.principalId = principalId; 81 | } 82 | } 83 | 84 | public class Oss 85 | { 86 | public readonly Bucket bucket; 87 | 88 | [JsonProperty("object")] 89 | public readonly Object obj; 90 | public readonly string ossSchemaVersion; 91 | public readonly string ruleId; 92 | 93 | [JsonConstructor] 94 | public Oss(Bucket bucket, 95 | Object obj, 96 | string ossSchemaVersion, 97 | string ruleId) 98 | { 99 | this.bucket = bucket; 100 | this.obj = obj; 101 | this.ossSchemaVersion = ossSchemaVersion; 102 | this.ruleId = ruleId; 103 | } 104 | } 105 | 106 | public class Event 107 | { 108 | public readonly string eventName; 109 | public readonly string eventSource; 110 | public readonly string eventTime; 111 | public readonly string eventVersion; 112 | public readonly Oss oss; 113 | public readonly string region; 114 | public readonly RequestParameters requestParameters; 115 | public readonly ResponseElements responseElements; 116 | public readonly UserIdentity userIdentity; 117 | 118 | [JsonConstructor] 119 | public Event(string eventName, 120 | string eventSource, 121 | string eventTime, 122 | string eventVersion, 123 | Oss oss, 124 | string region, 125 | RequestParameters requestParameters, 126 | ResponseElements responseElements, 127 | UserIdentity userIdentity) 128 | { 129 | this.eventName = eventName; 130 | this.eventSource = eventSource; 131 | this.eventTime = eventTime; 132 | this.eventVersion = eventVersion; 133 | this.oss = oss; 134 | this.region = region; 135 | this.requestParameters = requestParameters; 136 | this.responseElements = responseElements; 137 | this.userIdentity = userIdentity; 138 | } 139 | } 140 | 141 | public readonly Event[] events; 142 | 143 | [JsonConstructor] 144 | public OSSEvent(Event[] events) 145 | { 146 | this.events = events; 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /Aliyun.Serverless.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aliyun.Serverless.Core", "Aliyun.Serverless.Core\Aliyun.Serverless.Core.csproj", "{13F52F5D-8A6F-4853-B410-DC5A9B355BEC}" 5 | EndProject 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aliyun.Serverless.Events", "Aliyun.Serverless.Events\Aliyun.Serverless.Events.csproj", "{A74E7D38-8306-4119-B4E9-00BE0CA65CDC}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aliyun.Serverless.Core.Http", "Aliyun.Serverless.Core.Http\Aliyun.Serverless.Core.Http.csproj", "{0BB2FD98-DBAA-4A32-95A2-B0C53EEB3BBE}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aliyun.Serverless.Core.Mock", "Aliyun.Serverless.Core.Mock\Aliyun.Serverless.Core.Mock.csproj", "{07431B1D-FAB6-4280-860A-AC8DD6EFE16C}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {13F52F5D-8A6F-4853-B410-DC5A9B355BEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {13F52F5D-8A6F-4853-B410-DC5A9B355BEC}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {13F52F5D-8A6F-4853-B410-DC5A9B355BEC}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {13F52F5D-8A6F-4853-B410-DC5A9B355BEC}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {A74E7D38-8306-4119-B4E9-00BE0CA65CDC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {A74E7D38-8306-4119-B4E9-00BE0CA65CDC}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {A74E7D38-8306-4119-B4E9-00BE0CA65CDC}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {A74E7D38-8306-4119-B4E9-00BE0CA65CDC}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {0BB2FD98-DBAA-4A32-95A2-B0C53EEB3BBE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {0BB2FD98-DBAA-4A32-95A2-B0C53EEB3BBE}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {0BB2FD98-DBAA-4A32-95A2-B0C53EEB3BBE}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {0BB2FD98-DBAA-4A32-95A2-B0C53EEB3BBE}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {07431B1D-FAB6-4280-860A-AC8DD6EFE16C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {07431B1D-FAB6-4280-860A-AC8DD6EFE16C}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {07431B1D-FAB6-4280-860A-AC8DD6EFE16C}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {07431B1D-FAB6-4280-860A-AC8DD6EFE16C}.Release|Any CPU.Build.0 = Release|Any CPU 34 | EndGlobalSection 35 | EndGlobal 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Aliyun FunctionCompute C# Libraries 2 | ================================= 3 | 4 | [![Software License](https://img.shields.io/badge/license-apache2.0-brightgreen.svg)](LICENSE) 5 | [![GitHub version](https://badge.fury.io/gh/aliyun%2Ffc-dotnet-libs.svg)](https://badge.fury.io/gh/aliyun%2Ffc-dotnet-libs) 6 | [![Build Status](https://travis-ci.org/aliyun/fc-dotnet-libs.svg?branch=master)](https://travis-ci.org/aliyun/fc-dotnet-libs) 7 | 8 | Overview 9 | -------- 10 | 11 | The SDK of this version is dependent on the third-party library [Json.NET](https://www.newtonsoft.com/json). 12 | This componenent is for Aliyun FunctionCompute developers to build C# functions. 13 | 14 | Running environment 15 | ------------------- 16 | 17 | Applicable to .net core 2.1 or above 18 | 19 | 20 | Installation 21 | ------------------- 22 | 23 | #### Install the SDK through NuGet 24 | - If NuGet hasn't been installed for Visual Studio, install [NuGet](http://docs.nuget.org/docs/start-here/installing-nuget) first. 25 | 26 | - After NuGet is installed, access Visual Studio to create a project or open an existing project, and then select `TOOLS` > `NuGet Package Manager` > `Manage NuGet Packages for Solution`. 27 | 28 | - For normal invoke function, type `Aliyun.Serverless.Core` in the search box and click *Search*, select the latest version, and click *Install*. 29 | - For http invoke function, beside `Aliyun.Serverless.Core`, you also need to install `Aliyun.Serverless.Core.Http`. 30 | 31 | Getting started 32 | ------------------- 33 | 34 | ```csharp 35 | using System; 36 | using System.IO; 37 | using System.Threading.Tasks; 38 | using Aliyun.Serverless.Core; 39 | using Microsoft.Extensions.Logging; 40 | namespace samples 41 | { 42 | public class TestHandler 43 | { 44 | public async Task EchoEvent(Stream input, IFcContext context) 45 | { 46 | context.Logger.LogInformation("Handle Request: {0}", context.RequestId); 47 | MemoryStream memoryStream = new MemoryStream(); 48 | await input.CopyToAsync(memoryStream); 49 | return memoryStream; 50 | } 51 | } 52 | } 53 | ``` 54 | 55 | More resources 56 | -------------- 57 | - [Aliyun FunctionCompute docs](https://help.aliyun.com/product/50980.html) 58 | 59 | Contacting us 60 | ------------- 61 | - [Links](https://help.aliyun.com/document_detail/53087.html) 62 | --------------------------------------------------------------------------------