private static async Task <T> ConvertAndDeserialize <T>(string resourceName) where T : class { var context = GcfEventResources.CreateHttpContext(resourceName); var cloudEvent = await GcfConverters.ConvertGcfEventToCloudEvent(context.Request); return(CloudEventConverters.ConvertCloudEventData <T>(cloudEvent)); }
public string ReadCloudSchedulerData(CloudEvent cloudEvent) { _logger.LogInformation("Reading cloud scheduler data"); string country = null; switch (cloudEvent.Type) { case EVENT_TYPE_PUBSUB: var messagePublishedData = CloudEventConverters.ConvertCloudEventData <MessagePublishedData>(cloudEvent); var pubSubMessage = messagePublishedData.Message; _logger.LogInformation($"Type: {EVENT_TYPE_PUBSUB} data: {pubSubMessage.Data.ToBase64()}"); country = pubSubMessage.Data.ToStringUtf8(); break; case EVENT_TYPE_SCHEDULER: // Data: {"custom_data":"Q3lwcnVz"} var schedulerJobData = CloudEventConverters.ConvertCloudEventData <SchedulerJobData>(cloudEvent); _logger.LogInformation($"Type: {EVENT_TYPE_SCHEDULER} data: {schedulerJobData.CustomData.ToBase64()}"); country = schedulerJobData.CustomData.ToStringUtf8(); break; } _logger.LogInformation($"Extracted country: {country}"); return(country); }
public void ConvertEventData_Valid() { var evt = new CloudEvent("type", new Uri("//source")) { Data = "some text" }; var data = CloudEventConverters.ConvertCloudEventData <EventData>(evt); Assert.Equal("some text", data.Text); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } logger.LogInformation("Service is starting..."); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapPost("/", async context => { logger.LogInformation("Handling HTTP POST"); var ceId = context.Request.Headers["ce-id"]; if (string.IsNullOrEmpty(ceId)) { context.Response.StatusCode = StatusCodes.Status400BadRequest; await context.Response.WriteAsync("Bad Request: expected header ce-id"); return; } var cloudEvent = await context.Request.ReadCloudEventAsync(); var storageObjectData = CloudEventConverters.ConvertCloudEventData <StorageObjectData>(cloudEvent); logger.LogInformation( $"Detected change in GCS bucket: {storageObjectData.Bucket}, object name: {storageObjectData.Name}"); // reply with a cloudevent var replyEvent = new CloudEvent( CloudEventsSpecVersion.V1_0, "com.example.kuberun.events.received", new Uri("https://localhost"), Guid.NewGuid().ToString(), DateTime.Now) { DataContentType = new ContentType(MediaTypeNames.Application.Json), Data = JsonConvert.SerializeObject("Event received") }; // TODO: there should be a more concise way to construct the response. context.Response.StatusCode = StatusCodes.Status200OK; context.Response.Headers.Add("Ce-Id", replyEvent.Id); context.Response.Headers.Add("Ce-Specversion", "1.0"); context.Response.Headers.Add("Ce-Type", replyEvent.Type); context.Response.Headers.Add("Ce-Source", replyEvent.Source.ToString()); context.Response.ContentType = MediaTypeNames.Application.Json; await context.Response.WriteAsync(replyEvent.Data.ToString()); }); }); }
public (string, string) ReadCloudStorageData(CloudEvent cloudEvent) { _logger.LogInformation("Reading cloud storage data"); string bucket = null, name = null; switch (cloudEvent.Type) { case EVENT_TYPE_AUDITLOG: //"protoPayload" : {"resourceName":"projects/_/buckets/events-atamel-images-input/objects/atamel.jpg}"; var logEntryData = CloudEventConverters.ConvertCloudEventData <LogEntryData>(cloudEvent); var tokens = logEntryData.ProtoPayload.ResourceName.Split('/'); bucket = tokens[3]; name = tokens[5]; break; case EVENT_TYPE_STORAGE: var storageObjectData = CloudEventConverters.ConvertCloudEventData <StorageObjectData>(cloudEvent); bucket = storageObjectData.Bucket; name = storageObjectData.Name; break; case EVENT_TYPE_PUBSUB: // {"message": { // "data": "eyJidWNrZXQiOiJldmVudHMtYXRhbWVsLWltYWdlcy1pbnB1dCIsIm5hbWUiOiJiZWFjaC5qcGcifQ==", // },"subscription": "projects/events-atamel/subscriptions/cre-europe-west1-trigger-resizer-sub-000"} var messagePublishedData = CloudEventConverters.ConvertCloudEventData <MessagePublishedData>(cloudEvent); var pubSubMessage = messagePublishedData.Message; _logger.LogInformation($"Type: {EVENT_TYPE_PUBSUB} data: {pubSubMessage.Data.ToBase64()}"); var decoded = pubSubMessage.Data.ToStringUtf8(); _logger.LogInformation($"decoded: {decoded}"); var parsed = JValue.Parse(decoded); bucket = (string)parsed["bucket"]; name = (string)parsed["name"]; break; default: // Data: {"bucket":"knative-atamel-images-input","name":"beach.jpg"} _logger.LogInformation($"Type: {cloudEvent.Type} data: {cloudEvent.Data}"); var parsedCustom = JValue.Parse((string)cloudEvent.Data); bucket = (string)parsedCustom["bucket"]; name = (string)parsedCustom["name"]; break; } _logger.LogInformation($"Extracted bucket: {bucket}, name: {name}"); return(bucket, name); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } logger.LogInformation("Service is starting..."); app.UseRouting(); var bucketImages = GetEnvironmentVariable("BUCKET_IMAGES"); _bucketThumbnails = GetEnvironmentVariable("BUCKET_THUMBNAILS"); _projectId = GetEnvironmentVariable("PROJECT_ID"); app.UseEndpoints(endpoints => { endpoints.MapPost("/", async context => { var cloudEvent = await context.Request.ReadCloudEventAsync(); logger.LogInformation("Received CloudEvent\n" + GetEventLog(cloudEvent)); if (EVENT_TYPE_AUDITLOG != cloudEvent.Type) { logger.LogInformation($"Event type '{cloudEvent.Type}' is not {EVENT_TYPE_AUDITLOG}, ignoring."); return; } //"protoPayload" : {"resourceName":"projects/_/buckets/events-atamel-images-input/objects/atamel.jpg}"; var logEntryData = CloudEventConverters.ConvertCloudEventData <LogEntryData>(cloudEvent); var tokens = logEntryData.ProtoPayload.ResourceName.Split('/'); var bucket = tokens[3]; var objectName = tokens[5]; if (bucketImages != bucket) { logger.LogInformation($"Bucket '{bucket}' is not same as {bucketImages}, ignoring."); return; } await DeleteFromThumbnailsAsync(objectName, logger); await DeleteFromFirestore(objectName, logger); }); }); }
public (string, string) ReadCloudStorageData(CloudEvent cloudEvent) { _logger.LogInformation("Reading cloud storage data"); string bucket = null, name = null; switch (cloudEvent.Type) { case EVENT_TYPE_AUDITLOG: var logEntryData = CloudEventConverters.ConvertCloudEventData <LogEntryData>(cloudEvent); var tokens = logEntryData.ProtoPayload.ResourceName.Split('/'); bucket = tokens[3]; name = tokens[5]; break; case EVENT_TYPE_STORAGE: var storageObjectData = CloudEventConverters.ConvertCloudEventData <StorageObjectData>(cloudEvent); bucket = storageObjectData.Bucket; name = storageObjectData.Name; break; case EVENT_TYPE_PUBSUB: var messagePublishedData = CloudEventConverters.ConvertCloudEventData <MessagePublishedData>(cloudEvent); var pubSubMessage = messagePublishedData.Message; _logger.LogInformation($"Type: {EVENT_TYPE_PUBSUB} data: {pubSubMessage.Data.ToBase64()}"); var decoded = pubSubMessage.Data.ToStringUtf8(); _logger.LogInformation($"decoded: {decoded}"); var parsed = JValue.Parse(decoded); bucket = (string)parsed["bucket"]; name = (string)parsed["name"]; break; default: _logger.LogInformation($"Type: {cloudEvent.Type} data: {cloudEvent.Data}"); var parsedCustom = JValue.Parse((string)cloudEvent.Data); bucket = (string)parsedCustom["bucket"]; name = (string)parsedCustom["name"]; break; } _logger.LogInformation($"Extracted bucket: {bucket}, name: {name}"); return(bucket, name); }
/// <summary> /// Handles an HTTP request by extracting the Cloud Event from it, deserializing the data, and passing /// both the event and the data to the original Cloud Event Function. /// The request fails if it does not contain a Cloud Event. /// </summary> /// <param name="context">The HTTP context containing the request and response.</param> /// <returns>A task representing the asynchronous operation.</returns> public async Task HandleAsync(HttpContext context) { CloudEvent cloudEvent; TData data; try { cloudEvent = await CloudEventConverter.ConvertRequest(context.Request); data = CloudEventConverters.ConvertCloudEventData <TData>(cloudEvent); } catch (CloudEventConverter.ConversionException e) { _logger.LogError(e.Message); context.Response.StatusCode = 400; return; } await _function.HandleAsync(cloudEvent, data, context.RequestAborted); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } logger.LogInformation("Service is starting..."); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapPost("/", async context => { var cloudEvent = await context.Request.ReadCloudEventAsync(); logger.LogInformation("Received CloudEvent\n" + GetEventLog(cloudEvent)); var messagePublishedData = CloudEventConverters.ConvertCloudEventData <MessagePublishedData>(cloudEvent); var pubSubMessage = messagePublishedData.Message; if (pubSubMessage == null) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Bad request: Invalid Pub/Sub message format"); return; } var data = pubSubMessage.Data; logger.LogInformation($"Data: {data.ToBase64()}"); var name = data.ToStringUtf8(); logger.LogInformation($"Extracted name: {name}"); var id = context.Request.Headers["ce-id"]; await context.Response.WriteAsync($"Hello {name}! ID: {id}"); }); }); }