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
017/**
018 * Represents a Cloud Function that is activated by an event and parsed into a user-supplied class.
019 * The payload of the event is a JSON object, which is deserialized into a user-defined class as
020 * described for
021 * <a href="https://github.com/google/gson/blob/master/UserGuide.md#TOC-Object-Examples">Gson</a>.
022 *
023 * <p>Here is an example of an implementation that accesses the {@code messageId} property from
024 * a payload that matches a user-defined {@code PubSubMessage} class:
025 *
026 * <pre>
027 * public class Example implements {@code BackgroundFunction<PubSubMessage>} {
028 *   private static final Logger logger = Logger.getLogger(Example.class.getName());
029 *
030 *   {@code @Override}
031 *   public void accept(PubSubMessage pubSubMessage, Context context) {
032 *     logger.info("Got messageId " + pubSubMessage.messageId);
033 *   }
034 * }
035 *
036 * // Where PubSubMessage is a user-defined class like this:
037 * public class PubSubMessage {
038 *   String data;
039 *   {@code Map<String, String>} attributes;
040 *   String messageId;
041 *   String publishTime;
042 * }
043 * </pre>
044 *
045 * @param <T> the class of payload objects that this function expects.
046 */
047@FunctionalInterface
048public interface BackgroundFunction<T> {
049  /**
050   * Called to service an incoming event. This interface is implemented by user code to
051   * provide the action for a given background function. If this method throws any exception
052   * (including any {@link Error}) then the HTTP response will have a 500 status code.
053   *
054   * @param payload the payload of the event, deserialized from the original JSON string.
055   * @param context the context of the event. This is a set of values that every event has,
056   *     separately from the payload, such as timestamp and event type.
057   */
058  void accept(T payload, Context context) throws Exception;
059}