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 * <!-- The {@code} placement is a bit strange here, to prevent spurious spaces introduced by the
027 *      javadoc tool. -->
028 * <pre>
029 * public class Example implements{@code BackgroundFunction<PubSubMessage>} {
030 *   private static final Logger logger = Logger.getLogger(Example.class.getName());
031 *
032 *  {@code @Override}
033 *   public void accept(PubSubMessage pubSubMessage, Context context) {
034 *     logger.info("Got messageId " + pubSubMessage.messageId);
035 *   }
036 * }
037 *
038 * // Where PubSubMessage is a user-defined class like this:
039 * public class PubSubMessage {
040 *   String data;
041 *  {@code Map<String, String>} attributes;
042 *   String messageId;
043 *   String publishTime;
044 * }
045 * </pre>
046 *
047 * @param <T> the class of payload objects that this function expects.
048 */
049@FunctionalInterface
050public interface BackgroundFunction<T> {
051  /**
052   * Called to service an incoming event. This interface is implemented by user code to
053   * provide the action for a given background function. If this method throws any exception
054   * (including any {@link Error}) then the HTTP response will have a 500 status code.
055   *
056   * @param payload the payload of the event, deserialized from the original JSON string.
057   * @param context the context of the event. This is a set of values that every event has,
058   *     separately from the payload, such as timestamp and event type.
059   * @throws Exception to produce a 500 status code in the HTTP response.
060   */
061  void accept(T payload, Context context) throws Exception;
062}