001// Copyright 2019 Google LLC
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//      http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package com.google.cloud.functions;
016
017import com.google.gson.JsonElement;
018
019/**
020 * Represents a Cloud Function that is activated by an event.
021 *
022 * <p>Here is an example of an implementation that operates on the JSON payload of the event
023 * directly:
024 *
025 * <pre>
026 * public class Example implements BackgroundFunction {
027 *   private static final Logger logger = Logger.getLogger(Example.class.getName());
028 *
029 *   {@code @Override}
030 *   public void accept(JsonElement json, Context context) {
031 *     JsonElement messageId = json.getAsJsonObject().get("messageId");
032 *     String messageIdString = messageId.getAsJsonString();
033 *     logger.info("Got messageId " + messageIdString);
034 *   }
035 * }
036 * </pre>
037 *
038 * <p>Here is an example of an implementation that deserializes the JSON payload into a Java
039 * object for simpler access:
040 *
041 * <pre>
042 * public class Example implements BackgroundFunction {
043 *   private static final Logger logger = Logger.getLogger(Example.class.getName());
044 *
045 *   {@code @Override}
046 *   public void accept(JsonElement json, Context context) {
047 *     PubSubMessage message = Gson.fromJson(json, PubSubMessage.class);
048 *     logger.info("Got messageId " + message.messageId);
049 *   }
050 * }
051 *
052 * // Where PubSubMessage is a user-defined class like this:
053 * public class PubSubMessage {
054 *   String data;
055 *   {@code Map<String, String>} attributes;
056 *   String messageId;
057 *   String publishTime;
058 * }
059 * </pre>
060 */
061@FunctionalInterface
062public interface BackgroundFunction {
063  /**
064   * Called to service an incoming event. This interface is implemented by user code to
065   * provide the action for a given background function.
066   * (including any {@link Error}) then the HTTP response will have a 500 status code.
067   *
068   * @param json the payload of the event, as a parsed JSON object.
069   * @param context the context of the event. This is a set of values that every event has,
070   *     separately from the payload, such as timestamp and event type.
071   */
072  public void accept(JsonElement json, Context context);
073}