index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring/service/ChecklistService.java
package ai.driftkit.workflows.spring.service; import ai.driftkit.common.utils.TextSimilarityUtil; import ai.driftkit.workflows.core.domain.enhanced.EnhancedReasoningPlan; import ai.driftkit.workflows.spring.domain.ChecklistItemEntity; import ai.driftkit.workflows.spring.repository.ChecklistItemRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.PageRequest; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; /** * Service for managing checklist items in the reasoning-lite workflow */ @Slf4j @Service @RequiredArgsConstructor public class ChecklistService { private final ChecklistItemRepository checklistItemRepository; private static final double SIMILARITY_THRESHOLD = 0.85; private static final int DEFAULT_LIMIT = 300; // Cache for promptIds with expiry time private final AtomicReference<LocalDateTime> promptIdsCacheTime = new AtomicReference<>(LocalDateTime.MIN); private final AtomicReference<List<String>> promptIdsCache = new AtomicReference<>(new ArrayList<>()); private static final long CACHE_DURATION_MINUTES = 5; /** * Save checklist items from an EnhancedReasoningPlan * Fast implementation - just stores items without similarity checks * * @param plan The EnhancedReasoningPlan containing checklist items * @param promptId The ID of the prompt that generated this plan * @param query The original query */ public void saveChecklistItems(EnhancedReasoningPlan plan, String promptId, String query) { if (plan == null || plan.getChecklist() == null || plan.getChecklist().isEmpty()) { log.warn("No checklist items to save"); return; } if (query == null || query.isEmpty()) { log.error("Query cannot be null or empty when saving checklist items"); return; } log.info("Saving {} checklist items for promptId: {}, query: {}", plan.getChecklist().size(), promptId, query); List<ChecklistItemEntity> entities = new ArrayList<>(); for (EnhancedReasoningPlan.ChecklistItem item : plan.getChecklist()) { String normalizedDescription = TextSimilarityUtil.normalizeText(item.getDescription()); ChecklistItemEntity entity = ChecklistItemEntity.builder() .description(item.getDescription()) .severity(item.getSeverity().name()) .promptId(promptId) .query(query) .workflowType("reasoning-lite") .createdAt(LocalDateTime.now()) .useCount(1) .normalizedDescription(normalizedDescription) .build(); entities.add(entity); } // Just save them all without similarity checks - this is fast checklistItemRepository.saveAll(entities); log.info("Saved {} checklist items", entities.size()); } /** * Scheduled job to process newly added checklist items * Runs every hour to find similar items */ @Scheduled(cron = "0 0 * * * ?") // Every hour public void processSimilarities() { log.info("Starting scheduled similarity processing for checklist items"); // Get unprocessed items (where similarToId is null) with pagination List<ChecklistItemEntity> unprocessedItems = checklistItemRepository.findBySimilarToIdIsNull(PageRequest.of(0, 1000)); if (unprocessedItems.isEmpty()) { log.info("No unprocessed items found for similarity check"); return; } log.info("Processing {} unprocessed checklist items", unprocessedItems.size()); // Group by workflowType and promptId to process similar items together Map<String, List<ChecklistItemEntity>> groupedItems = unprocessedItems.stream() .collect(Collectors.groupingBy(item -> { String workflowType = item.getWorkflowType() != null ? item.getWorkflowType() : ""; String promptId = item.getPromptId() != null ? item.getPromptId() : ""; return workflowType + ":" + promptId; })); int processedCount = 0; List<ChecklistItemEntity> updatedItems = new ArrayList<>(); // Process each group separately for (List<ChecklistItemEntity> group : groupedItems.values()) { if (group.size() <= 1) { continue; // Skip groups with only one item } // Process the group for (int i = 0; i < group.size(); i++) { ChecklistItemEntity current = group.get(i); // Skip if already processed if (current.getSimilarToId() != null) { continue; } // Compare with other items in the same group for (int j = i + 1; j < group.size(); j++) { ChecklistItemEntity other = group.get(j); // Skip if already processed if (other.getSimilarToId() != null) { continue; } // Calculate similarity double similarity = TextSimilarityUtil.calculateSimilarity( current.getNormalizedDescription(), other.getNormalizedDescription()); if (similarity >= SIMILARITY_THRESHOLD) { // Mark the second item as similar to the first other.setSimilarToId(current.getId()); other.setSimilarityScore(similarity); updatedItems.add(other); processedCount++; } } } } // Save all updated items if (!updatedItems.isEmpty()) { checklistItemRepository.saveAll(updatedItems); } log.info("Similarity processing completed: updated {} items", processedCount); } /** * Scheduled job to clean up duplicate checklist items * Runs once a day to remove redundant items */ @Scheduled(cron = "0 0 3 * * ?") // 3 AM every day public void cleanupDuplicateItems() { log.info("Starting scheduled cleanup of duplicate checklist items"); // Get items marked as similar to others with pagination List<ChecklistItemEntity> similarItems = checklistItemRepository.findBySimilarToIdIsNotNull(PageRequest.of(0, 1000)); if (similarItems.isEmpty()) { log.info("No duplicate items found to clean up"); return; } // Group by similarToId Map<String, List<ChecklistItemEntity>> similarGroups = similarItems.stream() .collect(Collectors.groupingBy(ChecklistItemEntity::getSimilarToId)); int removedCount = 0; List<String> idsToRemove = new ArrayList<>(); List<ChecklistItemEntity> itemsToUpdate = new ArrayList<>(); // Process each group for (Map.Entry<String, List<ChecklistItemEntity>> entry : similarGroups.entrySet()) { String primaryId = entry.getKey(); List<ChecklistItemEntity> duplicates = entry.getValue(); // Find the primary item Optional<ChecklistItemEntity> primaryOpt = checklistItemRepository.findById(primaryId); if (primaryOpt.isPresent()) { ChecklistItemEntity primary = primaryOpt.get(); // Get items with very high similarity (above 0.95) List<ChecklistItemEntity> highSimilarityItems = duplicates.stream() .filter(item -> item.getSimilarityScore() != null && item.getSimilarityScore() > 0.95) .collect(Collectors.toList()); // Sum the use counts of high similarity items int additionalUseCount = highSimilarityItems.stream() .mapToInt(ChecklistItemEntity::getUseCount) .sum(); // Update the primary item's use count primary.setUseCount(primary.getUseCount() + additionalUseCount); itemsToUpdate.add(primary); // Add high similarity duplicate IDs to remove list idsToRemove.addAll(highSimilarityItems.stream() .map(ChecklistItemEntity::getId) .collect(Collectors.toList())); removedCount += highSimilarityItems.size(); } } // Save updated items and delete duplicates in batch operations if (!itemsToUpdate.isEmpty()) { checklistItemRepository.saveAll(itemsToUpdate); } if (!idsToRemove.isEmpty()) { checklistItemRepository.deleteAllById(idsToRemove); } log.info("Cleanup completed: removed {} duplicate checklist items", removedCount); } /** * Get all checklist items by promptId with default limit */ public List<ChecklistItemEntity> getChecklistItemsByPromptId(String promptId) { return checklistItemRepository.findByPromptId(promptId, PageRequest.of(0, DEFAULT_LIMIT)); } /** * Get all checklist items by query with default limit */ public List<ChecklistItemEntity> getChecklistItemsByQuery(String query) { return checklistItemRepository.findByQuery(query, PageRequest.of(0, DEFAULT_LIMIT)); } /** * Get all checklist items by promptId or query with default limit */ public List<ChecklistItemEntity> getChecklistItems(String promptId, String query) { if (promptId != null && !promptId.isEmpty()) { return checklistItemRepository.findByPromptId(promptId, PageRequest.of(0, DEFAULT_LIMIT)); } else if (query != null && !query.isEmpty()) { return checklistItemRepository.findByQuery(query, PageRequest.of(0, DEFAULT_LIMIT)); } return List.of(); } /** * Search checklist items by various criteria with default limit * * @param promptId Optional promptId to filter by * @param query Optional query to filter by (partial match) * @param description Optional description to filter by (partial match) * @return List of matching checklist items, limited to DEFAULT_LIMIT */ public List<ChecklistItemEntity> searchChecklistItems(String promptId, String query, String description) { List<ChecklistItemEntity> results = new ArrayList<>(); // If promptId is provided, that's the most specific search if (promptId != null && !promptId.isEmpty()) { results.addAll(checklistItemRepository.findByPromptId(promptId, PageRequest.of(0, DEFAULT_LIMIT))); } // If query is provided, search by query else if (query != null && !query.isEmpty()) { results.addAll(checklistItemRepository.findByQueryContaining(query, PageRequest.of(0, DEFAULT_LIMIT))); } // If neither promptId nor query is provided, but description is else if (description != null && !description.isEmpty()) { results.addAll(checklistItemRepository.findByDescriptionContaining(description, PageRequest.of(0, DEFAULT_LIMIT))); } // If no search criteria provided, return first PAGE_SIZE items without duplicates else { return checklistItemRepository.findBySimilarToIdIsNull(PageRequest.of(0, DEFAULT_LIMIT)); } // If description is also provided, filter the results further if (description != null && !description.isEmpty() && (promptId != null || query != null)) { results = results.stream() .filter(item -> item.getDescription().toLowerCase().contains(description.toLowerCase())) .limit(DEFAULT_LIMIT) .collect(Collectors.toList()); } return results; } /** * Get all unique promptIds that have checklist items, with caching */ public List<String> getAllPromptIds() { LocalDateTime now = LocalDateTime.now(); LocalDateTime cacheTime = promptIdsCacheTime.get(); // Check if cache is still valid (less than CACHE_DURATION_MINUTES old) if (ChronoUnit.MINUTES.between(cacheTime, now) < CACHE_DURATION_MINUTES) { return new ArrayList<>(promptIdsCache.get()); } // Cache expired, fetch fresh data List<String> promptIds = checklistItemRepository.findDistinctPromptIds(); // Remove duplicates Set<String> uniquePromptIds = new HashSet<>(promptIds); List<String> result = new ArrayList<>(uniquePromptIds); // Update cache promptIdsCache.set(result); promptIdsCacheTime.set(now); return result; } /** * Update an existing checklist item * * @param item The updated checklist item * @return The saved item */ public ChecklistItemEntity updateChecklistItem(ChecklistItemEntity item) { // First check if item exists if (!checklistItemRepository.existsById(item.getId())) { throw new IllegalArgumentException("Checklist item not found with ID: " + item.getId()); } // Ensure normalized description is updated if (item.getDescription() != null) { item.setNormalizedDescription(TextSimilarityUtil.normalizeText(item.getDescription())); } // Save the updated item return checklistItemRepository.save(item); } /** * Delete a checklist item by ID * * @param id The ID of the checklist item to delete */ public void deleteChecklistItem(String id) { // First check if item exists if (!checklistItemRepository.existsById(id)) { throw new IllegalArgumentException("Checklist item not found with ID: " + id); } // Check if other items reference this one as similar List<ChecklistItemEntity> similarItems = checklistItemRepository.findBySimilarToId(id, PageRequest.of(0, DEFAULT_LIMIT)); // If there are items that reference this one, clear their references if (!similarItems.isEmpty()) { for (ChecklistItemEntity similarItem : similarItems) { similarItem.setSimilarToId(null); similarItem.setSimilarityScore(null); checklistItemRepository.save(similarItem); } } // Now delete the item checklistItemRepository.deleteById(id); } }
0
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring/service/ImageModelService.java
package ai.driftkit.workflows.spring.service; import ai.driftkit.clients.core.ModelClientFactory; import ai.driftkit.common.domain.Grade; import ai.driftkit.common.domain.ImageMessageTask; import ai.driftkit.common.domain.ImageMessageTask.GeneratedImage; import ai.driftkit.common.domain.LLMRequest; import ai.driftkit.common.domain.MessageTask; import ai.driftkit.common.domain.client.ModelClient; import ai.driftkit.common.domain.client.ModelImageRequest; import ai.driftkit.common.domain.client.ModelImageResponse; import ai.driftkit.config.EtlConfig; import ai.driftkit.workflows.spring.domain.ImageMessageTaskEntity; import ai.driftkit.workflows.spring.domain.MessageTaskEntity; import ai.driftkit.workflows.spring.repository.ImageTaskRepository; import ai.driftkit.workflows.spring.repository.MessageTaskRepositoryV1; import jakarta.annotation.PostConstruct; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.stream.Collectors; @Slf4j @Service public class ImageModelService { @Autowired private ImageTaskRepository imageTaskRepository; @Autowired private MessageTaskRepositoryV1 messageTaskRepository; @Autowired private EtlConfig etlConfig; @Autowired private ModelRequestService modelRequestService; private ModelClient modelClient; private ExecutorService exec; @PostConstruct public void init() { this.modelClient = ModelClientFactory.fromConfig(etlConfig.getVault().get(0)); this.exec = Executors.newFixedThreadPool(Math.max(1, Runtime.getRuntime().availableProcessors() / 3)); } public MessageTask generateImage(MessageTask task, String query, int imagesNumber) { ImageMessageTask imageTask = addTaskSync(task, query, imagesNumber); task.setResponseTime(imageTask.getResponseTime()); task.setImageTaskId(imageTask.getMessageId()); MessageTaskEntity entity = MessageTaskEntity.fromMessageTask(task); messageTaskRepository.save(entity); return task; } public ImageMessageTask addTaskSync(MessageTask task, String query, int images) { try { ImageMessageTask imageMessageTask = ImageMessageTask.builder() .messageId(task.getMessageId()) .chatId(task.getChatId()) .message(query) .promptIds(task.getPromptIds()) .systemMessage(task.getSystemMessage()) .createdTime(System.currentTimeMillis()) .build(); ImageMessageTaskEntity entity = ImageMessageTaskEntity.fromImageMessageTask(imageMessageTask); imageTaskRepository.save(entity); return generate(task, imageMessageTask, Math.max(1, images)); } catch (Exception e) { log.error("Request to image generator is failed, chatId: [%s]".formatted(task.getChatId()), e); throw e; } } public ImageMessageTask rate(String messageId, Grade grade, String comment) { Optional<ImageMessageTaskEntity> entityOpt = imageTaskRepository.findById(messageId); if (entityOpt.isEmpty()) { return null; } ImageMessageTaskEntity entity = entityOpt.get(); entity.setGradeComment(comment); entity.setGrade(grade); imageTaskRepository.save(entity); return entity.toImageMessageTask(); } public Optional<ImageMessageTask> getImageMessageById(String messageId) { return imageTaskRepository.findById(messageId) .map(ImageMessageTaskEntity::toImageMessageTask); } public void describe(byte[] image) { } public ImageMessageTask generate(MessageTask task, ImageMessageTask request, int images) { // Get config for image model and quality EtlConfig.VaultConfig vaultConfig = etlConfig.getVault().get(0); // Create ModelImageRequest for the TraceableModelClient ModelImageRequest imageRequest = ModelImageRequest.builder() .prompt(request.getMessage()) .n(images) .model(task.getModelId() != null ? task.getModelId() : vaultConfig.getImageModel()) .quality(vaultConfig.getImageQuality()) .size(vaultConfig.getImageSize()) .build(); // Create request context for tracing ModelRequestContext requestContext = ModelRequestContext.builder() .contextId(request.getMessageId()) .promptText(request.getMessage()) .model(imageRequest.getModel()) .quality(imageRequest.getQuality()) .size(imageRequest.getSize()) .chatId(task.getChatId()) .purpose(task.getPurpose() != null ? task.getPurpose() : "image_generation") .build(); // Use ModelRequestService to handle the request (it uses TraceableModelClient internally) ModelImageResponse response = modelRequestService.textToImage(modelClient, imageRequest, requestContext); // Process the response if (response.getBytes() == null || response.getBytes().isEmpty()) { throw new RuntimeException("Empty image generation result for [%s]".formatted(request.getMessageId())); } request.setResponseTime(System.currentTimeMillis()); request.setImages(response.getBytes() .stream() .map(imageData -> { byte[] image = imageData.getImage(); String mimeType = imageData.getMimeType(); return GeneratedImage.builder() .data(image) .mimeType(mimeType) .revisedPrompt(response.getRevisedPrompt()) .build(); }) .collect(Collectors.toList()) ); ImageMessageTaskEntity entity = ImageMessageTaskEntity.fromImageMessageTask(request); imageTaskRepository.save(entity); return request; } @Data @NoArgsConstructor @AllArgsConstructor public static class ImageRequest extends LLMRequest { int images; public ImageRequest( String chatId, String message, List<String> promptIds, String systemMessage, String workflow, int images ) { super(chatId, message, promptIds, systemMessage, workflow, false, null, null, null, null, null, null, null, null, null); this.images = images; } } @Data @NoArgsConstructor @AllArgsConstructor public static class ImageTaskFuture { private String messageId; private Future<ImageMessageTask> future; } }
0
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring/service/LLMMemoryProvider.java
package ai.driftkit.workflows.spring.service; import ai.driftkit.common.domain.*; import ai.driftkit.workflows.core.chat.ChatMemory; import ai.driftkit.workflows.core.chat.TokenWindowChatMemory; import ai.driftkit.workflows.core.chat.SimpleTokenizer; import ai.driftkit.workflows.core.chat.Message; import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.Sort.Direction; import java.util.List; import java.util.Optional; public class LLMMemoryProvider { private final ChatService chatService; private final TasksService tasksService; public LLMMemoryProvider(ChatService chatService, TasksService tasksService) { this.chatService = chatService; this.tasksService = tasksService; } public void update(String chatId, List<MessageTask> messages) { tasksService.saveTasks(chatId, messages); } public ChatMemory get(String chatId) { Optional<Chat> chatOpt = chatService.getChat(String.valueOf(chatId)); if (chatOpt.isEmpty() || chatOpt.get().getMemoryLength() == 0) { return TokenWindowChatMemory.withMaxTokens(10000, new SimpleTokenizer()); } Chat chat = chatOpt.get(); ChatMemory chatMemory = TokenWindowChatMemory.withMaxTokens( chat.getMemoryLength(), new SimpleTokenizer() ); if (StringUtils.isNotBlank(chat.getSystemMessage())) { chatMemory.add(new Message( null, chat.getSystemMessage(), ChatMessageType.SYSTEM, MessageType.TEXT, null, null, null, null, null, chat.getCreatedTime(), chat.getCreatedTime(), null )); } List<Message> messages = tasksService.getMessagesList(chat.getChatId(), 0, 300, Direction.DESC); for (Message message : messages) { chatMemory.add(message); } return chatMemory; } }
0
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring/service/ModelRequestContext.java
package ai.driftkit.workflows.spring.service; import ai.driftkit.common.domain.MessageTask; import ai.driftkit.common.domain.client.ResponseFormat; import ai.driftkit.workflows.spring.domain.ModelRequestTrace.ContextType; import ai.driftkit.workflows.spring.domain.ModelRequestTrace.RequestType; import ai.driftkit.workflows.spring.domain.ModelRequestTrace.WorkflowInfo; import ai.driftkit.common.domain.client.ModelImageResponse.ModelContentMessage; import ai.driftkit.common.domain.client.ModelImageResponse.ModelContentMessage.ModelContentElement.ImageData; import lombok.Builder; import lombok.Data; import lombok.experimental.Accessors; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.util.List; import java.util.Map; @Data @Builder @Accessors(chain = true) public class ModelRequestContext { private String contextId; private ContextType contextType; private RequestType requestType; private String promptText; private String promptId; private Map<String, Object> variables; // Note: Prompt class removed for now - can be added later if needed private MessageTask messageTask; private List<ImageData> imageData; private WorkflowInfo workflowInfo; private List<ModelContentMessage> contextMessages; private Double temperature; private String model; private String quality; private String size; private String purpose; private String chatId; private ResponseFormat responseFormat; public static ModelRequestContextBuilder builder() { return new CustomModelRequestContextBuilder(); } public static class CustomModelRequestContextBuilder extends ModelRequestContextBuilder { @Override public ModelRequestContext build() { ModelRequestContext context = super.build(); // Prompt handling removed for now - can be added later if needed if (context.getMessageTask() != null) { MessageTask task = context.getMessageTask(); if (StringUtils.isEmpty(context.getContextId())) { context.setContextId(task.getMessageId()); context.setContextType(ContextType.MESSAGE_TASK); } if (StringUtils.isEmpty(context.getPromptText())) { context.setPromptText(task.getMessage()); } if (context.getVariables() == null) { context.setVariables(task.getVariables()); } if (StringUtils.isEmpty(context.getPromptId()) && CollectionUtils.isNotEmpty(task.getPromptIds())) { context.setPromptId(task.getPromptIds().get(0)); } if (StringUtils.isEmpty(context.getPurpose())) { context.setPurpose(task.getPurpose()); } if (StringUtils.isEmpty(context.getChatId())) { context.setChatId(task.getChatId()); } if (context.getResponseFormat() == null) { context.setResponseFormat(task.getResponseFormat()); } } if (context.getWorkflowInfo() != null) { if (context.getContextType() == null) { context.setContextType(ContextType.WORKFLOW); } if (StringUtils.isEmpty(context.getContextId()) && StringUtils.isNotEmpty(context.getWorkflowInfo().getWorkflowId())) { context.setContextId(context.getWorkflowInfo().getWorkflowId()); } } else if (context.getContextType() == ContextType.WORKFLOW && StringUtils.isNotEmpty(context.getContextId())) { WorkflowInfo workflowInfo = WorkflowInfo.builder() .workflowId(context.getContextId()) .build(); context.setWorkflowInfo(workflowInfo); } if (context.getContextType() == null && StringUtils.isNotEmpty(context.getContextId())) { context.setContextType(ContextType.CUSTOM); } if (StringUtils.isEmpty(context.getPromptText()) && CollectionUtils.isEmpty(context.getImageData())) { throw new IllegalArgumentException("Either promptText or imageData must be provided"); } return context; } } }
0
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring/service/ModelRequestService.java
package ai.driftkit.workflows.spring.service; import ai.driftkit.clients.openai.client.OpenAIModelClient; import ai.driftkit.common.domain.MessageTask; import ai.driftkit.common.domain.client.*; import ai.driftkit.common.domain.client.ResponseFormat; import ai.driftkit.context.core.util.PromptUtils; import ai.driftkit.workflows.spring.domain.ModelRequestTrace; import ai.driftkit.common.domain.client.ModelTextRequest.ModelTextRequestBuilder; import ai.driftkit.workflows.spring.repository.ModelRequestTraceRepository; import ai.driftkit.common.utils.AIUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; @Slf4j @Service public class ModelRequestService { private final ModelRequestTraceRepository traceRepository; private final Executor traceExecutor; public ModelRequestService(ModelRequestTraceRepository traceRepository, @Qualifier("workflowTraceExecutor") Executor traceExecutor) { this.traceRepository = traceRepository; this.traceExecutor = traceExecutor; } public ModelTextResponse textToText(ModelClient modelClient, ModelRequestContext context) { if (context.getRequestType() == null) { context.setRequestType(ModelRequestTrace.RequestType.TEXT_TO_TEXT); } String resolvedPrompt = context.getPromptText(); if (context.getVariables() != null && !context.getVariables().isEmpty()) { resolvedPrompt = PromptUtils.applyVariables(resolvedPrompt, context.getVariables()); } // Build request with context messages, temperature, model, and responseFormat if they exist ModelTextRequest request = buildTextRequest(modelClient, resolvedPrompt, context.getContextMessages(), context.getTemperature(), context.getModel(), context.getResponseFormat()); ModelTextResponse response; try { response = modelClient.textToText(request); MessageTask task = context.getMessageTask(); if (task != null) { task.updateWithResponseLogprobs(response); } } catch (Exception e) { log.error("Error sending text-to-text request to model", e); throw e; } if (response != null && response.getTrace() != null && StringUtils.isNotEmpty(context.getContextId())) { ModelRequestTrace trace = buildTextTrace(modelClient, context, request, response); CompletableFuture.runAsync(() -> saveTrace(trace), traceExecutor); } return response; } public ModelImageResponse textToImage(ModelClient modelClient, ModelRequestContext context) { if (context.getRequestType() == null) { context.setRequestType(ModelRequestTrace.RequestType.TEXT_TO_IMAGE); } String resolvedPrompt = context.getPromptText(); if (context.getVariables() != null && !context.getVariables().isEmpty()) { resolvedPrompt = PromptUtils.applyVariables(resolvedPrompt, context.getVariables()); } // Extract model, quality, and size from context if available String model = context.getModel(); String quality = context.getQuality(); String size = context.getSize(); ModelImageRequest request = buildImageRequest(modelClient, resolvedPrompt, model, quality, size); return textToImage(modelClient, request, context); } public ModelImageResponse textToImage(ModelClient modelClient, ModelImageRequest request, ModelRequestContext context) { if (context.getRequestType() == null) { context.setRequestType(ModelRequestTrace.RequestType.TEXT_TO_IMAGE); } ModelImageResponse response; try { response = modelClient.textToImage(request); } catch (Exception e) { log.error("Error sending text-to-image request to model", e); throw e; } if (response != null && response.getTrace() != null && StringUtils.isNotEmpty(context.getContextId())) { ModelRequestTrace trace = buildImageTrace(modelClient, context, request, response); CompletableFuture.runAsync(() -> saveTrace(trace), traceExecutor); } return response; } public ModelTextResponse imageToText(ModelClient modelClient, ModelRequestContext context) { if (context.getRequestType() == null) { context.setRequestType(ModelRequestTrace.RequestType.IMAGE_TO_TEXT); } String textPrompt = ""; if (StringUtils.isNotEmpty(context.getPromptText())) { textPrompt = context.getPromptText(); if (context.getVariables() != null && !context.getVariables().isEmpty()) { textPrompt = PromptUtils.applyVariables(textPrompt, context.getVariables()); } } ModelTextRequest request = buildImageTextRequest( modelClient, textPrompt, context.getImageData(), context.getTemperature(), context.getModel() ); ModelTextResponse response; try { response = modelClient.imageToText(request); MessageTask task = context.getMessageTask(); if (task != null) { task.updateWithResponseLogprobs(response); } } catch (Exception e) { log.error("Error sending image-to-text request to model", e); throw e; } if (response != null && response.getTrace() != null && StringUtils.isNotEmpty(context.getContextId())) { ModelRequestTrace trace = buildTextTrace(modelClient, context, request, response); CompletableFuture.runAsync(() -> saveTrace(trace), traceExecutor); } return response; } private ModelTextRequest buildTextRequest(ModelClient modelClient, String text) { return buildTextRequest(modelClient, text, null, null, null, null); } private ModelTextRequest buildTextRequest(ModelClient modelClient, String text, List<ModelImageResponse.ModelContentMessage> contextMessages) { return buildTextRequest(modelClient, text, contextMessages, null, null, null); } private ModelTextRequest buildTextRequest(ModelClient modelClient, String text, List<ModelImageResponse.ModelContentMessage> contextMessages, Double temperature) { return buildTextRequest(modelClient, text, contextMessages, temperature, null, null); } private ModelTextRequest buildTextRequest(ModelClient modelClient, String text, List<ModelImageResponse.ModelContentMessage> contextMessages, Double temperature, String model) { return buildTextRequest(modelClient, text, contextMessages, temperature, model, null); } private ModelTextRequest buildTextRequest(ModelClient modelClient, String text, List<ModelImageResponse.ModelContentMessage> contextMessages, Double temperature, String model, ResponseFormat responseFormat) { ModelTextRequestBuilder builder = ModelTextRequest.builder() .model(StringUtils.isNotBlank(model) ? model : Optional.ofNullable(modelClient.getModel()).orElse(OpenAIModelClient.GPT_DEFAULT)) .temperature(temperature != null ? temperature : modelClient.getTemperature()); if (responseFormat != null) { builder.responseFormat(responseFormat); } if (CollectionUtils.isNotEmpty(contextMessages)) { List<ModelImageResponse.ModelContentMessage> messages = new ArrayList<>(contextMessages); if (StringUtils.isNotBlank(text)) { messages.add(ModelImageResponse.ModelContentMessage.create(Role.user, text)); } builder.messages(messages); } else { builder.messages(List.of(ModelImageResponse.ModelContentMessage.create(Role.user, text))); } return builder.build(); } private ModelImageRequest buildImageRequest(ModelClient modelClient, String prompt) { return buildImageRequest(modelClient, prompt, null, null, null); } private ModelImageRequest buildImageRequest(ModelClient modelClient, String prompt, String model, String quality, String size) { return ModelImageRequest.builder() .model(StringUtils.isNotBlank(model) ? model : modelClient.getModel()) .prompt(prompt) .quality(quality) .size(size) .build(); } private ModelTextRequest buildImageTextRequest(ModelClient modelClient, String text, ModelImageResponse.ModelContentMessage.ModelContentElement.ImageData imageData) { return buildImageTextRequest(modelClient, text, imageData, null, null); } private ModelTextRequest buildImageTextRequest(ModelClient modelClient, String text, ModelImageResponse.ModelContentMessage.ModelContentElement.ImageData imageData, Double temperature, String model) { return ModelTextRequest.builder() .model(StringUtils.isNotBlank(model) ? model : Optional.ofNullable(modelClient.getModel()).orElse(OpenAIModelClient.GPT_DEFAULT)) .temperature(temperature != null ? temperature : modelClient.getTemperature()) .messages(List.of(ModelImageResponse.ModelContentMessage.create(Role.user, text, imageData))) .build(); } private ModelTextRequest buildImageTextRequest(ModelClient modelClient, String text, List<ModelImageResponse.ModelContentMessage.ModelContentElement.ImageData> imageData, Double temperature, String model) { return ModelTextRequest.builder() .model(StringUtils.isNotBlank(model) ? model : Optional.ofNullable(modelClient.getModel()).orElse(OpenAIModelClient.GPT_DEFAULT)) .temperature(temperature != null ? temperature : modelClient.getTemperature()) .messages(List.of(ModelImageResponse.ModelContentMessage.create(Role.user, List.of(text), imageData))) .build(); } private ModelRequestTrace buildTextTrace(ModelClient modelClient, ModelRequestContext context, ModelTextRequest request, ModelTextResponse response) { String modelId = request.getModel() != null ? request.getModel() : modelClient.getModel(); return ModelRequestTrace.fromTextResponse( context.getContextId(), context.getContextType(), context.getRequestType(), context.getPromptText(), context.getPromptId(), context.getVariables(), modelId, response, context.getWorkflowInfo(), context.getPurpose(), context.getChatId() ); } private ModelRequestTrace buildImageTrace(ModelClient modelClient, ModelRequestContext context, ModelImageRequest request, ModelImageResponse response) { String modelId = request.getModel() != null ? request.getModel() : modelClient.getModel(); return ModelRequestTrace.fromImageResponse( context.getContextId(), context.getContextType(), context.getPromptText(), context.getPromptId(), context.getVariables(), modelId, response, context.getWorkflowInfo(), context.getPurpose(), context.getChatId() ); } private void saveTrace(ModelRequestTrace trace) { try { traceRepository.save(trace); } catch (Exception e) { log.error("Error saving model request trace", e); } } }
0
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring/service/TasksService.java
package ai.driftkit.workflows.spring.service; import ai.driftkit.common.domain.*; import ai.driftkit.workflows.core.chat.Message; import ai.driftkit.workflows.spring.domain.ChatEntity; import ai.driftkit.workflows.spring.domain.MessageTaskEntity; import ai.driftkit.workflows.spring.repository.ChatRepository; import ai.driftkit.workflows.spring.repository.MessageTaskRepositoryV1; import ai.driftkit.workflows.spring.service.AIService.LLMTaskFuture; import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Service; import javax.validation.constraints.NotNull; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; import java.util.stream.Stream; @Service @RequiredArgsConstructor public class TasksService { private final MessageTaskRepositoryV1 messageTaskRepository; private final ChatRepository chatRepository; private final AIService aiService; private ExecutorService exec; @PostConstruct public void init() { this.exec = Executors.newFixedThreadPool(Math.max(1, Runtime.getRuntime().availableProcessors() / 2)); } public LLMTaskFuture addTask(MessageTask messageTask) { Chat chat = null; if (messageTask.getChatId() != null) { Optional<ChatEntity> chatOpt = chatRepository.findById(messageTask.getChatId()); if (chatOpt.isPresent()) { chat = chatOpt.get(); } } String systemMessage = messageTask.getSystemMessage() != null || chat == null ? messageTask.getSystemMessage() : chat.getSystemMessage(); Language language = messageTask.getLanguage() != null || chat == null ? messageTask.getLanguage() : chat.getLanguage(); if (language == null) { language = Language.ENGLISH; // default } messageTask.setSystemMessage(systemMessage); messageTask.setLanguage(language); MessageTaskEntity entity = MessageTaskEntity.fromMessageTask(messageTask); messageTaskRepository.save(entity); return new LLMTaskFuture( messageTask.getMessageId(), exec.submit(() -> aiService.chat(messageTask)) ); } public MessageTask rate(String messageId, Grade grade, String comment) { MessageTaskEntity entity = messageTaskRepository.findById(messageId).orElse(null); if (entity == null) { return null; } entity.setGradeComment(comment); entity.setGrade(grade); messageTaskRepository.save(entity); return MessageTaskEntity.toMessageTask(entity); } public Optional<MessageTask> getTaskByMessageId(String messageId) { return messageTaskRepository.findById(messageId) .map(MessageTaskEntity::toMessageTask); } public List<MessageTask> getTasksByChatId(String chatId, int skip, int limit, Direction direction) { int page = skip / limit; PageRequest pageRequest = PageRequest.of(page, limit, Sort.by(direction, "createdTime")); Page<MessageTaskEntity> messageTaskPage = messageTaskRepository.findByChatId(chatId, pageRequest); return messageTaskPage.getContent().stream() .map(MessageTaskEntity::toMessageTask) .collect(Collectors.toList()); } public List<MessageTask> getTasks(int skip, int limit, Direction direction) { int page = skip / limit; PageRequest pageRequest = PageRequest.of(page, limit, Sort.by(direction, "createdTime")); Page<MessageTaskEntity> messageTaskPage = messageTaskRepository.findAll(pageRequest); return messageTaskPage.getContent().stream() .map(MessageTaskEntity::toMessageTask) .collect(Collectors.toList()); } @NotNull public List<Message> getMessagesList(String chatId, Integer skip, Integer limit, Direction direction) { return getTasksByChatId(chatId, skip, limit, direction) .stream() .flatMap(TasksService::toMessages) .filter(Objects::nonNull) .collect(Collectors.toList()); } @org.jetbrains.annotations.NotNull private static Stream<Message> toMessages(MessageTask e) { Message result = null; if (e.getResult() == null) { if (e.getImageTaskId() != null) { result = new Message( e.getMessageId(), null, ChatMessageType.AI, MessageType.IMAGE, e.getImageTaskId(), e.getGrade() != null ? ai.driftkit.workflows.core.chat.Grade.valueOf(e.getGrade().name()) : null, e.getGradeComment(), e.getWorkflow(), e.getContextJson(), e.getCreatedTime(), e.getCreatedTime(), e.getResponseTime() ); } } else { result = new Message( e.getMessageId(), e.getResult(), ChatMessageType.AI, MessageType.TEXT, e.getImageTaskId(), e.getGrade() != null ? ai.driftkit.workflows.core.chat.Grade.valueOf(e.getGrade().name()) : null, e.getGradeComment(), e.getWorkflow(), e.getContextJson(), e.getCreatedTime(), e.getCreatedTime(), e.getResponseTime() ); } return Stream.of( new Message( e.getMessageId(), e.getMessage(), ChatMessageType.USER, MessageType.TEXT, null, null, null, null, null, e.getCreatedTime(), e.getCreatedTime(), null ), result ); } public void saveTasks(String chatId, List<MessageTask> messages) { List<MessageTaskEntity> entities = messages.stream() .map(message -> { message.setChatId(chatId); return MessageTaskEntity.fromMessageTask(message); }) .collect(Collectors.toList()); messageTaskRepository.saveAll(entities); } }
0
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring
java-sources/ai/driftkit/driftkit-workflows-spring-boot-starter/0.8.1/ai/driftkit/workflows/spring/tracing/SpringRequestTracingProvider.java
package ai.driftkit.workflows.spring.tracing; import ai.driftkit.common.domain.client.ModelTextRequest; import ai.driftkit.common.domain.client.ModelTextResponse; import ai.driftkit.common.domain.client.ModelImageRequest; import ai.driftkit.common.domain.client.ModelImageResponse; import ai.driftkit.common.domain.client.Role; import ai.driftkit.workflows.core.agent.RequestTracingProvider; import ai.driftkit.workflows.core.agent.RequestTracingRegistry; import ai.driftkit.workflows.spring.domain.ModelRequestTrace; import ai.driftkit.workflows.spring.repository.ModelRequestTraceRepository; import ai.driftkit.common.utils.AIUtils; import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.stereotype.Component; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.stream.Collectors; /** * Spring-based implementation of RequestTracingProvider that provides full * tracing capabilities for LLMAgent requests using ModelRequestTrace repository. */ @Slf4j @Component @RequiredArgsConstructor public class SpringRequestTracingProvider implements RequestTracingProvider { private final ModelRequestTraceRepository traceRepository; private final Executor traceExecutor; @PostConstruct public void registerSelf() { RequestTracingRegistry.register(this); log.info("SpringRequestTracingProvider registered in RequestTracingRegistry"); } @Override public void traceTextRequest(ModelTextRequest request, ModelTextResponse response, RequestContext context) { if (response == null || response.getTrace() == null || context.getContextId() == null) { return; } try { ModelRequestTrace trace = buildTextTrace(request, response, context); CompletableFuture.runAsync(() -> saveTrace(trace), traceExecutor); log.debug("Traced text request for agent: {} with context type: {}", context.getContextId(), context.getContextType()); } catch (Exception e) { log.error("Error tracing text request for agent: {}", context.getContextId(), e); } } @Override public void traceImageRequest(ModelImageRequest request, ModelImageResponse response, RequestContext context) { if (response == null || response.getTrace() == null || context.getContextId() == null) { return; } try { ModelRequestTrace trace = buildImageTrace(request, response, context); CompletableFuture.runAsync(() -> saveTrace(trace), traceExecutor); log.debug("Traced image generation request for agent: {} with context type: {}", context.getContextId(), context.getContextType()); } catch (Exception e) { log.error("Error tracing image request for agent: {}", context.getContextId(), e); } } @Override public void traceImageToTextRequest(ModelTextRequest request, ModelTextResponse response, RequestContext context) { if (response == null || response.getTrace() == null || context.getContextId() == null) { return; } try { ModelRequestTrace trace = buildImageToTextTrace(request, response, context); CompletableFuture.runAsync(() -> saveTrace(trace), traceExecutor); log.debug("Traced image-to-text request for agent: {} with context type: {}", context.getContextId(), context.getContextType()); } catch (Exception e) { log.error("Error tracing image-to-text request for agent: {}", context.getContextId(), e); } } private ModelRequestTrace buildTextTrace(ModelTextRequest request, ModelTextResponse response, RequestContext context) { return ModelRequestTrace.builder() .id(AIUtils.generateId()) // Unique trace ID .requestType(ModelRequestTrace.RequestType.TEXT_TO_TEXT) .contextType(ModelRequestTrace.ContextType.AGENT) .contextId(context.getContextId()) // Agent ID .timestamp(System.currentTimeMillis()) .promptTemplate(extractPromptTemplate(request)) .promptId(context.getPromptId()) .variables(convertVariables(context.getVariables())) .modelId(response.getTrace() != null ? response.getTrace().getModel() : null) .responseId(response.getId()) .response(response.getResponse()) .trace(response.getTrace()) .chatId(context.getChatId()) .purpose("AGENT_" + context.getContextType()) .build(); } private ModelRequestTrace buildImageTrace(ModelImageRequest request, ModelImageResponse response, RequestContext context) { return ModelRequestTrace.builder() .id(AIUtils.generateId()) // Unique trace ID .requestType(ModelRequestTrace.RequestType.TEXT_TO_IMAGE) .contextType(ModelRequestTrace.ContextType.AGENT) .contextId(context.getContextId()) // Agent ID .timestamp(System.currentTimeMillis()) .promptTemplate(request.getPrompt()) .promptId(context.getPromptId()) .variables(convertVariables(context.getVariables())) .modelId(response.getTrace() != null ? response.getTrace().getModel() : null) .trace(response.getTrace()) .chatId(context.getChatId()) .purpose("AGENT_" + context.getContextType()) .build(); } private ModelRequestTrace buildImageToTextTrace(ModelTextRequest request, ModelTextResponse response, RequestContext context) { return ModelRequestTrace.builder() .id(AIUtils.generateId()) // Unique trace ID .requestType(ModelRequestTrace.RequestType.IMAGE_TO_TEXT) .contextType(ModelRequestTrace.ContextType.AGENT) .contextId(context.getContextId()) // Agent ID .timestamp(System.currentTimeMillis()) .promptTemplate(extractPromptTemplate(request)) .promptId(context.getPromptId()) .variables(convertVariables(context.getVariables())) .modelId(response.getTrace() != null ? response.getTrace().getModel() : null) .responseId(response.getId()) .response(response.getResponse()) .trace(response.getTrace()) .chatId(context.getChatId()) .purpose("AGENT_" + context.getContextType()) .build(); } private Map<String, String> convertVariables(Map<String, Object> variables) { if (variables == null) { return null; } return variables.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> entry.getValue() != null ? entry.getValue().toString() : null )); } private String extractPromptTemplate(ModelTextRequest request) { if (request.getMessages() == null || CollectionUtils.isEmpty(request.getMessages())) { return null; } // Find the last user message as prompt template return request.getMessages().stream() .filter(msg -> msg.getRole() == Role.user) .reduce((first, second) -> second) // Get the last user message .map(msg -> msg.getContent() != null ? msg.getContent().toString() : null) .orElse(null); } private void saveTrace(ModelRequestTrace trace) { try { traceRepository.save(trace); log.trace("Saved trace: {} for agent: {}", trace.getId(), trace.getContextId()); } catch (Exception e) { log.error("Failed to save trace: {} for agent: {}", trace.getId(), trace.getContextId(), e); } } }
0
java-sources/ai/edgestore/engine/1.0.1-alpha03/ai/edgestore
java-sources/ai/edgestore/engine/1.0.1-alpha03/ai/edgestore/engine/Lib.java
package ai.edgestore.engine; public class Lib { }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/data/Transport.java
package ai.eloquent.data; import ai.eloquent.raft.RaftLifecycle; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; /** * An interface for a transport layer used in the Eloquent codebase. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public interface Transport { /** * Bind a consumer to this transport, to listen on incoming messages. * * @param channel The type of message we're listing for. * @param listener The listener, taking as input a raw byte stream. */ void bind(UDPBroadcastProtos.MessageType channel, Consumer<byte[]> listener); /** * Send a message on the transport. * * @param destination The location we're sending the message to. This is transport-dependent, but is often * the IP address of the destination. * @param messageType The type of message we're sending. This should match the channel in {@link #bind(UDPBroadcastProtos.MessageType, Consumer)}. * @param message The message, as a raw byte stream. * * @return True if the message was sent. */ boolean sendTransport(String destination, UDPBroadcastProtos.MessageType messageType, byte[] message); /** * Broadcast a message to everyone listening on the transport. * * @param messageType The type of message we're sending. This should match the channel in {@link #bind(UDPBroadcastProtos.MessageType, Consumer)}. * @param message The message, as a raw byte stream. * * @return True if the message was sent to everyone. */ boolean broadcastTransport(UDPBroadcastProtos.MessageType messageType, byte[] message); /** * A thread pool from which to run tasks. */ ExecutorService POOL = RaftLifecycle.global.managedThreadPool("TransportWorker", true); // we need this to be core for Raft /** * Do a given action. * This method is called on the main IO reader loop; if we want to offload it to a thread, * this is the place to do it. * * @param async If true, run the action asynchronously on {@link #POOL}. * @param description A human-readable description of the action * @param action The action to perform. */ @SuppressWarnings("unused") default void doAction(boolean async, String description, Runnable action) { if (async && !POOL.isShutdown()) { POOL.submit(action); } else { action.run(); } } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/data/UDPBroadcastProtos.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: UDPBroadcast.proto package ai.eloquent.data; public final class UDPBroadcastProtos { private UDPBroadcastProtos() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } /** * Protobuf enum {@code ai.eloquent.MessageType} */ public enum MessageType implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> ** A raft message * </pre> * * <code>RAFT = 0;</code> */ RAFT(0), /** * <pre> ** A cache invalidation message for {&#64;link EloquentCache}. This is distinct from {&#64;link FRONTEND_REFRESH}, which refreshes a frontend's cache. * </pre> * * <code>CACHE = 1;</code> */ CACHE(1), /** * <pre> ** A routine ping * </pre> * * <code>PING = 2;</code> */ PING(2), /** * <pre> ** An indication that we should re-index a given document. * </pre> * * <code>REINDEX = 3;</code> */ REINDEX(3), /** * <pre> ** Refresh a cache entry on the frontend. This is distinct from {&#64;link CACHE}, which invalidates an {&#64;link EloquentCache} * </pre> * * <code>FRONTEND_REFRESH = 4;</code> */ FRONTEND_REFRESH(4), UNRECOGNIZED(-1), ; /** * <pre> ** A raft message * </pre> * * <code>RAFT = 0;</code> */ public static final int RAFT_VALUE = 0; /** * <pre> ** A cache invalidation message for {&#64;link EloquentCache}. This is distinct from {&#64;link FRONTEND_REFRESH}, which refreshes a frontend's cache. * </pre> * * <code>CACHE = 1;</code> */ public static final int CACHE_VALUE = 1; /** * <pre> ** A routine ping * </pre> * * <code>PING = 2;</code> */ public static final int PING_VALUE = 2; /** * <pre> ** An indication that we should re-index a given document. * </pre> * * <code>REINDEX = 3;</code> */ public static final int REINDEX_VALUE = 3; /** * <pre> ** Refresh a cache entry on the frontend. This is distinct from {&#64;link CACHE}, which invalidates an {&#64;link EloquentCache} * </pre> * * <code>FRONTEND_REFRESH = 4;</code> */ public static final int FRONTEND_REFRESH_VALUE = 4; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static MessageType valueOf(int value) { return forNumber(value); } public static MessageType forNumber(int value) { switch (value) { case 0: return RAFT; case 1: return CACHE; case 2: return PING; case 3: return REINDEX; case 4: return FRONTEND_REFRESH; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<MessageType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< MessageType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<MessageType>() { public MessageType findValueByNumber(int number) { return MessageType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return ai.eloquent.data.UDPBroadcastProtos.getDescriptor().getEnumTypes().get(0); } private static final MessageType[] VALUES = values(); public static MessageType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private MessageType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:ai.eloquent.MessageType) } public interface CacheInvalidateMessageOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.CacheInvalidateMessage) com.google.protobuf.MessageOrBuilder { /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 1;</code> */ java.lang.String getName(); /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 1;</code> */ com.google.protobuf.ByteString getNameBytes(); /** * <pre> ** The key we're invalidating. * </pre> * * <code>bytes key = 2;</code> */ com.google.protobuf.ByteString getKey(); /** * <pre> ** If true, we're invalidating the entire cache. * </pre> * * <code>bool clear_all = 3;</code> */ boolean getClearAll(); } /** * <pre> ** * A message indicating the cache and key that we should clear. * </pre> * * Protobuf type {@code ai.eloquent.CacheInvalidateMessage} */ public static final class CacheInvalidateMessage extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.CacheInvalidateMessage) CacheInvalidateMessageOrBuilder { private static final long serialVersionUID = 0L; // Use CacheInvalidateMessage.newBuilder() to construct. private CacheInvalidateMessage(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CacheInvalidateMessage() { name_ = ""; key_ = com.google.protobuf.ByteString.EMPTY; clearAll_ = false; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private CacheInvalidateMessage( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 18: { key_ = input.readBytes(); break; } case 24: { clearAll_ = input.readBool(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_CacheInvalidateMessage_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_CacheInvalidateMessage_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage.class, ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int KEY_FIELD_NUMBER = 2; private com.google.protobuf.ByteString key_; /** * <pre> ** The key we're invalidating. * </pre> * * <code>bytes key = 2;</code> */ public com.google.protobuf.ByteString getKey() { return key_; } public static final int CLEAR_ALL_FIELD_NUMBER = 3; private boolean clearAll_; /** * <pre> ** If true, we're invalidating the entire cache. * </pre> * * <code>bool clear_all = 3;</code> */ public boolean getClearAll() { return clearAll_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!key_.isEmpty()) { output.writeBytes(2, key_); } if (clearAll_ != false) { output.writeBool(3, clearAll_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!key_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, key_); } if (clearAll_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, clearAll_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage)) { return super.equals(obj); } ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage other = (ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage) obj; boolean result = true; result = result && getName() .equals(other.getName()); result = result && getKey() .equals(other.getKey()); result = result && (getClearAll() == other.getClearAll()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + KEY_FIELD_NUMBER; hash = (53 * hash) + getKey().hashCode(); hash = (37 * hash) + CLEAR_ALL_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getClearAll()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> ** * A message indicating the cache and key that we should clear. * </pre> * * Protobuf type {@code ai.eloquent.CacheInvalidateMessage} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.CacheInvalidateMessage) ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessageOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_CacheInvalidateMessage_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_CacheInvalidateMessage_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage.class, ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage.Builder.class); } // Construct using ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); name_ = ""; key_ = com.google.protobuf.ByteString.EMPTY; clearAll_ = false; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_CacheInvalidateMessage_descriptor; } public ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage getDefaultInstanceForType() { return ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage.getDefaultInstance(); } public ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage build() { ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage buildPartial() { ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage result = new ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage(this); result.name_ = name_; result.key_ = key_; result.clearAll_ = clearAll_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage) { return mergeFrom((ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage other) { if (other == ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (other.getKey() != com.google.protobuf.ByteString.EMPTY) { setKey(other.getKey()); } if (other.getClearAll() != false) { setClearAll(other.getClearAll()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object name_ = ""; /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 1;</code> */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 1;</code> */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 1;</code> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private com.google.protobuf.ByteString key_ = com.google.protobuf.ByteString.EMPTY; /** * <pre> ** The key we're invalidating. * </pre> * * <code>bytes key = 2;</code> */ public com.google.protobuf.ByteString getKey() { return key_; } /** * <pre> ** The key we're invalidating. * </pre> * * <code>bytes key = 2;</code> */ public Builder setKey(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } key_ = value; onChanged(); return this; } /** * <pre> ** The key we're invalidating. * </pre> * * <code>bytes key = 2;</code> */ public Builder clearKey() { key_ = getDefaultInstance().getKey(); onChanged(); return this; } private boolean clearAll_ ; /** * <pre> ** If true, we're invalidating the entire cache. * </pre> * * <code>bool clear_all = 3;</code> */ public boolean getClearAll() { return clearAll_; } /** * <pre> ** If true, we're invalidating the entire cache. * </pre> * * <code>bool clear_all = 3;</code> */ public Builder setClearAll(boolean value) { clearAll_ = value; onChanged(); return this; } /** * <pre> ** If true, we're invalidating the entire cache. * </pre> * * <code>bool clear_all = 3;</code> */ public Builder clearClearAll() { clearAll_ = false; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.CacheInvalidateMessage) } // @@protoc_insertion_point(class_scope:ai.eloquent.CacheInvalidateMessage) private static final ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage(); } public static ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CacheInvalidateMessage> PARSER = new com.google.protobuf.AbstractParser<CacheInvalidateMessage>() { public CacheInvalidateMessage parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CacheInvalidateMessage(input, extensionRegistry); } }; public static com.google.protobuf.Parser<CacheInvalidateMessage> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CacheInvalidateMessage> getParserForType() { return PARSER; } public ai.eloquent.data.UDPBroadcastProtos.CacheInvalidateMessage getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ReindexDocumentOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.ReindexDocument) com.google.protobuf.MessageOrBuilder { /** * <pre> ** The UUID of the document we are reindexing. * </pre> * * <code>string uuid = 1;</code> */ java.lang.String getUuid(); /** * <pre> ** The UUID of the document we are reindexing. * </pre> * * <code>string uuid = 1;</code> */ com.google.protobuf.ByteString getUuidBytes(); } /** * <pre> ** * A message indicating that we should re-index a document everywhere on * the cluster. * </pre> * * Protobuf type {@code ai.eloquent.ReindexDocument} */ public static final class ReindexDocument extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.ReindexDocument) ReindexDocumentOrBuilder { private static final long serialVersionUID = 0L; // Use ReindexDocument.newBuilder() to construct. private ReindexDocument(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ReindexDocument() { uuid_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ReindexDocument( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); uuid_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_ReindexDocument_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_ReindexDocument_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.data.UDPBroadcastProtos.ReindexDocument.class, ai.eloquent.data.UDPBroadcastProtos.ReindexDocument.Builder.class); } public static final int UUID_FIELD_NUMBER = 1; private volatile java.lang.Object uuid_; /** * <pre> ** The UUID of the document we are reindexing. * </pre> * * <code>string uuid = 1;</code> */ public java.lang.String getUuid() { java.lang.Object ref = uuid_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uuid_ = s; return s; } } /** * <pre> ** The UUID of the document we are reindexing. * </pre> * * <code>string uuid = 1;</code> */ public com.google.protobuf.ByteString getUuidBytes() { java.lang.Object ref = uuid_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uuid_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getUuidBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, uuid_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getUuidBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, uuid_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.data.UDPBroadcastProtos.ReindexDocument)) { return super.equals(obj); } ai.eloquent.data.UDPBroadcastProtos.ReindexDocument other = (ai.eloquent.data.UDPBroadcastProtos.ReindexDocument) obj; boolean result = true; result = result && getUuid() .equals(other.getUuid()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + UUID_FIELD_NUMBER; hash = (53 * hash) + getUuid().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.data.UDPBroadcastProtos.ReindexDocument prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> ** * A message indicating that we should re-index a document everywhere on * the cluster. * </pre> * * Protobuf type {@code ai.eloquent.ReindexDocument} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.ReindexDocument) ai.eloquent.data.UDPBroadcastProtos.ReindexDocumentOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_ReindexDocument_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_ReindexDocument_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.data.UDPBroadcastProtos.ReindexDocument.class, ai.eloquent.data.UDPBroadcastProtos.ReindexDocument.Builder.class); } // Construct using ai.eloquent.data.UDPBroadcastProtos.ReindexDocument.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); uuid_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_ReindexDocument_descriptor; } public ai.eloquent.data.UDPBroadcastProtos.ReindexDocument getDefaultInstanceForType() { return ai.eloquent.data.UDPBroadcastProtos.ReindexDocument.getDefaultInstance(); } public ai.eloquent.data.UDPBroadcastProtos.ReindexDocument build() { ai.eloquent.data.UDPBroadcastProtos.ReindexDocument result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.data.UDPBroadcastProtos.ReindexDocument buildPartial() { ai.eloquent.data.UDPBroadcastProtos.ReindexDocument result = new ai.eloquent.data.UDPBroadcastProtos.ReindexDocument(this); result.uuid_ = uuid_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.data.UDPBroadcastProtos.ReindexDocument) { return mergeFrom((ai.eloquent.data.UDPBroadcastProtos.ReindexDocument)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.data.UDPBroadcastProtos.ReindexDocument other) { if (other == ai.eloquent.data.UDPBroadcastProtos.ReindexDocument.getDefaultInstance()) return this; if (!other.getUuid().isEmpty()) { uuid_ = other.uuid_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.data.UDPBroadcastProtos.ReindexDocument parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.data.UDPBroadcastProtos.ReindexDocument) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object uuid_ = ""; /** * <pre> ** The UUID of the document we are reindexing. * </pre> * * <code>string uuid = 1;</code> */ public java.lang.String getUuid() { java.lang.Object ref = uuid_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uuid_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** The UUID of the document we are reindexing. * </pre> * * <code>string uuid = 1;</code> */ public com.google.protobuf.ByteString getUuidBytes() { java.lang.Object ref = uuid_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uuid_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** The UUID of the document we are reindexing. * </pre> * * <code>string uuid = 1;</code> */ public Builder setUuid( java.lang.String value) { if (value == null) { throw new NullPointerException(); } uuid_ = value; onChanged(); return this; } /** * <pre> ** The UUID of the document we are reindexing. * </pre> * * <code>string uuid = 1;</code> */ public Builder clearUuid() { uuid_ = getDefaultInstance().getUuid(); onChanged(); return this; } /** * <pre> ** The UUID of the document we are reindexing. * </pre> * * <code>string uuid = 1;</code> */ public Builder setUuidBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); uuid_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.ReindexDocument) } // @@protoc_insertion_point(class_scope:ai.eloquent.ReindexDocument) private static final ai.eloquent.data.UDPBroadcastProtos.ReindexDocument DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.data.UDPBroadcastProtos.ReindexDocument(); } public static ai.eloquent.data.UDPBroadcastProtos.ReindexDocument getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ReindexDocument> PARSER = new com.google.protobuf.AbstractParser<ReindexDocument>() { public ReindexDocument parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ReindexDocument(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ReindexDocument> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ReindexDocument> getParserForType() { return PARSER; } public ai.eloquent.data.UDPBroadcastProtos.ReindexDocument getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface FrontendRefreshMessageOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.FrontendRefreshMessage) com.google.protobuf.MessageOrBuilder { /** * <pre> ** The username that owns this cache element. * </pre> * * <code>string username = 1;</code> */ java.lang.String getUsername(); /** * <pre> ** The username that owns this cache element. * </pre> * * <code>string username = 1;</code> */ com.google.protobuf.ByteString getUsernameBytes(); /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 2;</code> */ java.lang.String getName(); /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 2;</code> */ com.google.protobuf.ByteString getNameBytes(); /** * <pre> ** The key we're invalidating. * </pre> * * <code>string key = 3;</code> */ java.lang.String getKey(); /** * <pre> ** The key we're invalidating. * </pre> * * <code>string key = 3;</code> */ com.google.protobuf.ByteString getKeyBytes(); /** * <pre> ** The JSON of the value we're invalidating. * </pre> * * <code>string value_json = 4;</code> */ java.lang.String getValueJson(); /** * <pre> ** The JSON of the value we're invalidating. * </pre> * * <code>string value_json = 4;</code> */ com.google.protobuf.ByteString getValueJsonBytes(); } /** * <pre> ** * A message indicating a frontend cache should be refreshed with a new value. * </pre> * * Protobuf type {@code ai.eloquent.FrontendRefreshMessage} */ public static final class FrontendRefreshMessage extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.FrontendRefreshMessage) FrontendRefreshMessageOrBuilder { private static final long serialVersionUID = 0L; // Use FrontendRefreshMessage.newBuilder() to construct. private FrontendRefreshMessage(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private FrontendRefreshMessage() { username_ = ""; name_ = ""; key_ = ""; valueJson_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private FrontendRefreshMessage( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); username_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); key_ = s; break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); valueJson_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_FrontendRefreshMessage_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_FrontendRefreshMessage_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage.class, ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage.Builder.class); } public static final int USERNAME_FIELD_NUMBER = 1; private volatile java.lang.Object username_; /** * <pre> ** The username that owns this cache element. * </pre> * * <code>string username = 1;</code> */ public java.lang.String getUsername() { java.lang.Object ref = username_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); username_ = s; return s; } } /** * <pre> ** The username that owns this cache element. * </pre> * * <code>string username = 1;</code> */ public com.google.protobuf.ByteString getUsernameBytes() { java.lang.Object ref = username_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); username_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NAME_FIELD_NUMBER = 2; private volatile java.lang.Object name_; /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 2;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 2;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int KEY_FIELD_NUMBER = 3; private volatile java.lang.Object key_; /** * <pre> ** The key we're invalidating. * </pre> * * <code>string key = 3;</code> */ public java.lang.String getKey() { java.lang.Object ref = key_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); key_ = s; return s; } } /** * <pre> ** The key we're invalidating. * </pre> * * <code>string key = 3;</code> */ public com.google.protobuf.ByteString getKeyBytes() { java.lang.Object ref = key_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); key_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALUE_JSON_FIELD_NUMBER = 4; private volatile java.lang.Object valueJson_; /** * <pre> ** The JSON of the value we're invalidating. * </pre> * * <code>string value_json = 4;</code> */ public java.lang.String getValueJson() { java.lang.Object ref = valueJson_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); valueJson_ = s; return s; } } /** * <pre> ** The JSON of the value we're invalidating. * </pre> * * <code>string value_json = 4;</code> */ public com.google.protobuf.ByteString getValueJsonBytes() { java.lang.Object ref = valueJson_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); valueJson_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getUsernameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, username_); } if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, name_); } if (!getKeyBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, key_); } if (!getValueJsonBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, valueJson_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getUsernameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, username_); } if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, name_); } if (!getKeyBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, key_); } if (!getValueJsonBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, valueJson_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage)) { return super.equals(obj); } ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage other = (ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage) obj; boolean result = true; result = result && getUsername() .equals(other.getUsername()); result = result && getName() .equals(other.getName()); result = result && getKey() .equals(other.getKey()); result = result && getValueJson() .equals(other.getValueJson()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + USERNAME_FIELD_NUMBER; hash = (53 * hash) + getUsername().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + KEY_FIELD_NUMBER; hash = (53 * hash) + getKey().hashCode(); hash = (37 * hash) + VALUE_JSON_FIELD_NUMBER; hash = (53 * hash) + getValueJson().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> ** * A message indicating a frontend cache should be refreshed with a new value. * </pre> * * Protobuf type {@code ai.eloquent.FrontendRefreshMessage} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.FrontendRefreshMessage) ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessageOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_FrontendRefreshMessage_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_FrontendRefreshMessage_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage.class, ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage.Builder.class); } // Construct using ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); username_ = ""; name_ = ""; key_ = ""; valueJson_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_FrontendRefreshMessage_descriptor; } public ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage getDefaultInstanceForType() { return ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage.getDefaultInstance(); } public ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage build() { ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage buildPartial() { ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage result = new ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage(this); result.username_ = username_; result.name_ = name_; result.key_ = key_; result.valueJson_ = valueJson_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage) { return mergeFrom((ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage other) { if (other == ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage.getDefaultInstance()) return this; if (!other.getUsername().isEmpty()) { username_ = other.username_; onChanged(); } if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (!other.getKey().isEmpty()) { key_ = other.key_; onChanged(); } if (!other.getValueJson().isEmpty()) { valueJson_ = other.valueJson_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object username_ = ""; /** * <pre> ** The username that owns this cache element. * </pre> * * <code>string username = 1;</code> */ public java.lang.String getUsername() { java.lang.Object ref = username_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); username_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** The username that owns this cache element. * </pre> * * <code>string username = 1;</code> */ public com.google.protobuf.ByteString getUsernameBytes() { java.lang.Object ref = username_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); username_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** The username that owns this cache element. * </pre> * * <code>string username = 1;</code> */ public Builder setUsername( java.lang.String value) { if (value == null) { throw new NullPointerException(); } username_ = value; onChanged(); return this; } /** * <pre> ** The username that owns this cache element. * </pre> * * <code>string username = 1;</code> */ public Builder clearUsername() { username_ = getDefaultInstance().getUsername(); onChanged(); return this; } /** * <pre> ** The username that owns this cache element. * </pre> * * <code>string username = 1;</code> */ public Builder setUsernameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); username_ = value; onChanged(); return this; } private java.lang.Object name_ = ""; /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 2;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 2;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 2;</code> */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 2;</code> */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <pre> ** The name of the cache we're invalidating a key in. * </pre> * * <code>string name = 2;</code> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private java.lang.Object key_ = ""; /** * <pre> ** The key we're invalidating. * </pre> * * <code>string key = 3;</code> */ public java.lang.String getKey() { java.lang.Object ref = key_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); key_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** The key we're invalidating. * </pre> * * <code>string key = 3;</code> */ public com.google.protobuf.ByteString getKeyBytes() { java.lang.Object ref = key_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); key_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** The key we're invalidating. * </pre> * * <code>string key = 3;</code> */ public Builder setKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } key_ = value; onChanged(); return this; } /** * <pre> ** The key we're invalidating. * </pre> * * <code>string key = 3;</code> */ public Builder clearKey() { key_ = getDefaultInstance().getKey(); onChanged(); return this; } /** * <pre> ** The key we're invalidating. * </pre> * * <code>string key = 3;</code> */ public Builder setKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); key_ = value; onChanged(); return this; } private java.lang.Object valueJson_ = ""; /** * <pre> ** The JSON of the value we're invalidating. * </pre> * * <code>string value_json = 4;</code> */ public java.lang.String getValueJson() { java.lang.Object ref = valueJson_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); valueJson_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** The JSON of the value we're invalidating. * </pre> * * <code>string value_json = 4;</code> */ public com.google.protobuf.ByteString getValueJsonBytes() { java.lang.Object ref = valueJson_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); valueJson_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** The JSON of the value we're invalidating. * </pre> * * <code>string value_json = 4;</code> */ public Builder setValueJson( java.lang.String value) { if (value == null) { throw new NullPointerException(); } valueJson_ = value; onChanged(); return this; } /** * <pre> ** The JSON of the value we're invalidating. * </pre> * * <code>string value_json = 4;</code> */ public Builder clearValueJson() { valueJson_ = getDefaultInstance().getValueJson(); onChanged(); return this; } /** * <pre> ** The JSON of the value we're invalidating. * </pre> * * <code>string value_json = 4;</code> */ public Builder setValueJsonBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); valueJson_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.FrontendRefreshMessage) } // @@protoc_insertion_point(class_scope:ai.eloquent.FrontendRefreshMessage) private static final ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage(); } public static ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<FrontendRefreshMessage> PARSER = new com.google.protobuf.AbstractParser<FrontendRefreshMessage>() { public FrontendRefreshMessage parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new FrontendRefreshMessage(input, extensionRegistry); } }; public static com.google.protobuf.Parser<FrontendRefreshMessage> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<FrontendRefreshMessage> getParserForType() { return PARSER; } public ai.eloquent.data.UDPBroadcastProtos.FrontendRefreshMessage getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface UDPPacketOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.UDPPacket) com.google.protobuf.MessageOrBuilder { /** * <pre> ** The actual contents of the message. * </pre> * * <code>bytes contents = 1;</code> */ com.google.protobuf.ByteString getContents(); /** * <pre> ** A flag to type. * </pre> * * <code>.ai.eloquent.MessageType type = 2;</code> */ int getTypeValue(); /** * <pre> ** A flag to type. * </pre> * * <code>.ai.eloquent.MessageType type = 2;</code> */ ai.eloquent.data.UDPBroadcastProtos.MessageType getType(); /** * <pre> ** The server that sent this message. * </pre> * * <code>string sender = 3;</code> */ java.lang.String getSender(); /** * <pre> ** The server that sent this message. * </pre> * * <code>string sender = 3;</code> */ com.google.protobuf.ByteString getSenderBytes(); /** * <pre> ** If true, this packet is a broadcast packet. * </pre> * * <code>bool is_broadcast = 4;</code> */ boolean getIsBroadcast(); } /** * <pre> ** * A message we'd be sending over UDP, along with metadata * </pre> * * Protobuf type {@code ai.eloquent.UDPPacket} */ public static final class UDPPacket extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.UDPPacket) UDPPacketOrBuilder { private static final long serialVersionUID = 0L; // Use UDPPacket.newBuilder() to construct. private UDPPacket(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UDPPacket() { contents_ = com.google.protobuf.ByteString.EMPTY; type_ = 0; sender_ = ""; isBroadcast_ = false; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private UDPPacket( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { contents_ = input.readBytes(); break; } case 16: { int rawValue = input.readEnum(); type_ = rawValue; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); sender_ = s; break; } case 32: { isBroadcast_ = input.readBool(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_UDPPacket_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_UDPPacket_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.data.UDPBroadcastProtos.UDPPacket.class, ai.eloquent.data.UDPBroadcastProtos.UDPPacket.Builder.class); } public static final int CONTENTS_FIELD_NUMBER = 1; private com.google.protobuf.ByteString contents_; /** * <pre> ** The actual contents of the message. * </pre> * * <code>bytes contents = 1;</code> */ public com.google.protobuf.ByteString getContents() { return contents_; } public static final int TYPE_FIELD_NUMBER = 2; private int type_; /** * <pre> ** A flag to type. * </pre> * * <code>.ai.eloquent.MessageType type = 2;</code> */ public int getTypeValue() { return type_; } /** * <pre> ** A flag to type. * </pre> * * <code>.ai.eloquent.MessageType type = 2;</code> */ public ai.eloquent.data.UDPBroadcastProtos.MessageType getType() { ai.eloquent.data.UDPBroadcastProtos.MessageType result = ai.eloquent.data.UDPBroadcastProtos.MessageType.valueOf(type_); return result == null ? ai.eloquent.data.UDPBroadcastProtos.MessageType.UNRECOGNIZED : result; } public static final int SENDER_FIELD_NUMBER = 3; private volatile java.lang.Object sender_; /** * <pre> ** The server that sent this message. * </pre> * * <code>string sender = 3;</code> */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } } /** * <pre> ** The server that sent this message. * </pre> * * <code>string sender = 3;</code> */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int IS_BROADCAST_FIELD_NUMBER = 4; private boolean isBroadcast_; /** * <pre> ** If true, this packet is a broadcast packet. * </pre> * * <code>bool is_broadcast = 4;</code> */ public boolean getIsBroadcast() { return isBroadcast_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!contents_.isEmpty()) { output.writeBytes(1, contents_); } if (type_ != ai.eloquent.data.UDPBroadcastProtos.MessageType.RAFT.getNumber()) { output.writeEnum(2, type_); } if (!getSenderBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, sender_); } if (isBroadcast_ != false) { output.writeBool(4, isBroadcast_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!contents_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, contents_); } if (type_ != ai.eloquent.data.UDPBroadcastProtos.MessageType.RAFT.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, type_); } if (!getSenderBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, sender_); } if (isBroadcast_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, isBroadcast_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.data.UDPBroadcastProtos.UDPPacket)) { return super.equals(obj); } ai.eloquent.data.UDPBroadcastProtos.UDPPacket other = (ai.eloquent.data.UDPBroadcastProtos.UDPPacket) obj; boolean result = true; result = result && getContents() .equals(other.getContents()); result = result && type_ == other.type_; result = result && getSender() .equals(other.getSender()); result = result && (getIsBroadcast() == other.getIsBroadcast()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CONTENTS_FIELD_NUMBER; hash = (53 * hash) + getContents().hashCode(); hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; hash = (37 * hash) + SENDER_FIELD_NUMBER; hash = (53 * hash) + getSender().hashCode(); hash = (37 * hash) + IS_BROADCAST_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getIsBroadcast()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.data.UDPBroadcastProtos.UDPPacket prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> ** * A message we'd be sending over UDP, along with metadata * </pre> * * Protobuf type {@code ai.eloquent.UDPPacket} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.UDPPacket) ai.eloquent.data.UDPBroadcastProtos.UDPPacketOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_UDPPacket_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_UDPPacket_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.data.UDPBroadcastProtos.UDPPacket.class, ai.eloquent.data.UDPBroadcastProtos.UDPPacket.Builder.class); } // Construct using ai.eloquent.data.UDPBroadcastProtos.UDPPacket.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); contents_ = com.google.protobuf.ByteString.EMPTY; type_ = 0; sender_ = ""; isBroadcast_ = false; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.data.UDPBroadcastProtos.internal_static_ai_eloquent_UDPPacket_descriptor; } public ai.eloquent.data.UDPBroadcastProtos.UDPPacket getDefaultInstanceForType() { return ai.eloquent.data.UDPBroadcastProtos.UDPPacket.getDefaultInstance(); } public ai.eloquent.data.UDPBroadcastProtos.UDPPacket build() { ai.eloquent.data.UDPBroadcastProtos.UDPPacket result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.data.UDPBroadcastProtos.UDPPacket buildPartial() { ai.eloquent.data.UDPBroadcastProtos.UDPPacket result = new ai.eloquent.data.UDPBroadcastProtos.UDPPacket(this); result.contents_ = contents_; result.type_ = type_; result.sender_ = sender_; result.isBroadcast_ = isBroadcast_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.data.UDPBroadcastProtos.UDPPacket) { return mergeFrom((ai.eloquent.data.UDPBroadcastProtos.UDPPacket)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.data.UDPBroadcastProtos.UDPPacket other) { if (other == ai.eloquent.data.UDPBroadcastProtos.UDPPacket.getDefaultInstance()) return this; if (other.getContents() != com.google.protobuf.ByteString.EMPTY) { setContents(other.getContents()); } if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } if (!other.getSender().isEmpty()) { sender_ = other.sender_; onChanged(); } if (other.getIsBroadcast() != false) { setIsBroadcast(other.getIsBroadcast()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.data.UDPBroadcastProtos.UDPPacket parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.data.UDPBroadcastProtos.UDPPacket) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private com.google.protobuf.ByteString contents_ = com.google.protobuf.ByteString.EMPTY; /** * <pre> ** The actual contents of the message. * </pre> * * <code>bytes contents = 1;</code> */ public com.google.protobuf.ByteString getContents() { return contents_; } /** * <pre> ** The actual contents of the message. * </pre> * * <code>bytes contents = 1;</code> */ public Builder setContents(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); return this; } /** * <pre> ** The actual contents of the message. * </pre> * * <code>bytes contents = 1;</code> */ public Builder clearContents() { contents_ = getDefaultInstance().getContents(); onChanged(); return this; } private int type_ = 0; /** * <pre> ** A flag to type. * </pre> * * <code>.ai.eloquent.MessageType type = 2;</code> */ public int getTypeValue() { return type_; } /** * <pre> ** A flag to type. * </pre> * * <code>.ai.eloquent.MessageType type = 2;</code> */ public Builder setTypeValue(int value) { type_ = value; onChanged(); return this; } /** * <pre> ** A flag to type. * </pre> * * <code>.ai.eloquent.MessageType type = 2;</code> */ public ai.eloquent.data.UDPBroadcastProtos.MessageType getType() { ai.eloquent.data.UDPBroadcastProtos.MessageType result = ai.eloquent.data.UDPBroadcastProtos.MessageType.valueOf(type_); return result == null ? ai.eloquent.data.UDPBroadcastProtos.MessageType.UNRECOGNIZED : result; } /** * <pre> ** A flag to type. * </pre> * * <code>.ai.eloquent.MessageType type = 2;</code> */ public Builder setType(ai.eloquent.data.UDPBroadcastProtos.MessageType value) { if (value == null) { throw new NullPointerException(); } type_ = value.getNumber(); onChanged(); return this; } /** * <pre> ** A flag to type. * </pre> * * <code>.ai.eloquent.MessageType type = 2;</code> */ public Builder clearType() { type_ = 0; onChanged(); return this; } private java.lang.Object sender_ = ""; /** * <pre> ** The server that sent this message. * </pre> * * <code>string sender = 3;</code> */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** The server that sent this message. * </pre> * * <code>string sender = 3;</code> */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** The server that sent this message. * </pre> * * <code>string sender = 3;</code> */ public Builder setSender( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sender_ = value; onChanged(); return this; } /** * <pre> ** The server that sent this message. * </pre> * * <code>string sender = 3;</code> */ public Builder clearSender() { sender_ = getDefaultInstance().getSender(); onChanged(); return this; } /** * <pre> ** The server that sent this message. * </pre> * * <code>string sender = 3;</code> */ public Builder setSenderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sender_ = value; onChanged(); return this; } private boolean isBroadcast_ ; /** * <pre> ** If true, this packet is a broadcast packet. * </pre> * * <code>bool is_broadcast = 4;</code> */ public boolean getIsBroadcast() { return isBroadcast_; } /** * <pre> ** If true, this packet is a broadcast packet. * </pre> * * <code>bool is_broadcast = 4;</code> */ public Builder setIsBroadcast(boolean value) { isBroadcast_ = value; onChanged(); return this; } /** * <pre> ** If true, this packet is a broadcast packet. * </pre> * * <code>bool is_broadcast = 4;</code> */ public Builder clearIsBroadcast() { isBroadcast_ = false; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.UDPPacket) } // @@protoc_insertion_point(class_scope:ai.eloquent.UDPPacket) private static final ai.eloquent.data.UDPBroadcastProtos.UDPPacket DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.data.UDPBroadcastProtos.UDPPacket(); } public static ai.eloquent.data.UDPBroadcastProtos.UDPPacket getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UDPPacket> PARSER = new com.google.protobuf.AbstractParser<UDPPacket>() { public UDPPacket parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new UDPPacket(input, extensionRegistry); } }; public static com.google.protobuf.Parser<UDPPacket> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UDPPacket> getParserForType() { return PARSER; } public ai.eloquent.data.UDPBroadcastProtos.UDPPacket getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_CacheInvalidateMessage_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_CacheInvalidateMessage_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_ReindexDocument_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_ReindexDocument_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_FrontendRefreshMessage_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_FrontendRefreshMessage_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_UDPPacket_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_UDPPacket_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\022UDPBroadcast.proto\022\013ai.eloquent\"F\n\026Cac" + "heInvalidateMessage\022\014\n\004name\030\001 \001(\t\022\013\n\003key" + "\030\002 \001(\014\022\021\n\tclear_all\030\003 \001(\010\"\037\n\017ReindexDocu" + "ment\022\014\n\004uuid\030\001 \001(\t\"Y\n\026FrontendRefreshMes" + "sage\022\020\n\010username\030\001 \001(\t\022\014\n\004name\030\002 \001(\t\022\013\n\003" + "key\030\003 \001(\t\022\022\n\nvalue_json\030\004 \001(\t\"k\n\tUDPPack" + "et\022\020\n\010contents\030\001 \001(\014\022&\n\004type\030\002 \001(\0162\030.ai." + "eloquent.MessageType\022\016\n\006sender\030\003 \001(\t\022\024\n\014" + "is_broadcast\030\004 \001(\010*O\n\013MessageType\022\010\n\004RAF" + "T\020\000\022\t\n\005CACHE\020\001\022\010\n\004PING\020\002\022\013\n\007REINDEX\020\003\022\024\n" + "\020FRONTEND_REFRESH\020\004B&\n\020ai.eloquent.dataB" + "\022UDPBroadcastProtosb\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_ai_eloquent_CacheInvalidateMessage_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_ai_eloquent_CacheInvalidateMessage_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_CacheInvalidateMessage_descriptor, new java.lang.String[] { "Name", "Key", "ClearAll", }); internal_static_ai_eloquent_ReindexDocument_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_ai_eloquent_ReindexDocument_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_ReindexDocument_descriptor, new java.lang.String[] { "Uuid", }); internal_static_ai_eloquent_FrontendRefreshMessage_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_ai_eloquent_FrontendRefreshMessage_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_FrontendRefreshMessage_descriptor, new java.lang.String[] { "Username", "Name", "Key", "ValueJson", }); internal_static_ai_eloquent_UDPPacket_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_ai_eloquent_UDPPacket_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_UDPPacket_descriptor, new java.lang.String[] { "Contents", "Type", "Sender", "IsBroadcast", }); } // @@protoc_insertion_point(outer_class_scope) }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/data/UDPTransport.java
package ai.eloquent.data; import ai.eloquent.io.IOUtils; import ai.eloquent.monitoring.Prometheus; import ai.eloquent.raft.RaftLifecycle; import ai.eloquent.util.*; import com.google.protobuf.ByteString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.net.*; import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import java.util.regex.Pattern; /** * A class (usually instantiated as a singleton) to send and receive messages over UDP. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class UDPTransport implements Transport { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(UDPTransport.class); /** * A regexp for detecting an IP address. */ private static final Pattern IP_REGEX = Pattern.compile("^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); /** * The port we are listening to UDP messages on. */ private static final int DEFAULT_UDP_LISTEN_PORT = 42888; /** * The port we are listening to UDP messages on. */ private static final int DEFAULT_TCP_LISTEN_PORT = 42888; /** * The maximum size of a UDP packet, before we should fault in TCP. */ private static final int MAX_UDP_PACKET_SIZE = 65000; // actually 65,507 bytes, will be reduced by the MTU of underlying layers /** * A little helper to prevent spamming errors when the network is down. */ private static boolean networkSeemsDown = false; /** * The name we should assign ourselves on the transport. */ public final InetAddress serverName; /** * {@link #serverName}'s {@link InetAddress#getHostAddress()} */ private final String serverAddress; /** * If true, run the handling of messages on the transport in a new thread. */ public final boolean thread; /** * If true, zip packets on the network. This takes ~2x as much CPU, but * lowers packet size. */ public final boolean zip; /** * The addresses we should broadcast messages to. */ private InetAddress[] broadcastAddrs; /** * If true, the broadcast address at {@link #broadcastAddrs} is a real broadcast address. * Otherwise, it's just a list of addresses in the cluster. */ private final boolean isRealBroadcast; /** * The time when our last message was received. This is mostly for debugging. */ private long lastMessageReceived = 0L; /** * The time when our last message was sent. This is mostly for debugging. */ private long lastMessageSent = 0L; /** * The port we are listening to UDP messages on. */ private final int udpListenPort; /** * The port we are listening to TCP messages on. */ private final int tcpListenPort; /** * A shared socket to write messages to. */ private DatagramSocket socket; /** * The server socket. */ private DatagramSocket serverSocket; /** * The set of listeners on the broadcast. */ private final Map<UDPBroadcastProtos.MessageType, IdentityHashSet<Consumer<byte[]>>> listeners = new HashMap<>(); /** * Register the hosts that have received pings, and the times they received them. */ private final Map<byte[], Long> pingsReceived = new HashMap<>(); /** * The inferred MTU (Maximum Transmission Unit) of this transport */ public final int mtu; /** * If true, allow sending of "jumbo packets" (fragmented packets) larger than * the MTU of the interface. On one hand, this allows for UDP with larger packet sizes; * on the other hand, this may be unstable / slower on the open internet, vs a known * local area network. */ public final boolean allowJumboPackets; /** * A queue of messages to send asynchronously. */ private final Queue<Runnable> sendQueue = new ArrayDeque<>(); /** * Timing statistics for Raft. */ Object summaryTimer = Prometheus.summaryBuild("udp_transport", "Statistics on the UDP Transport calls", "operation"); /** * Create a UDP transport. * * @param udpListenPort The UDP port to listen on. * @param tcpListenPort The TCP port to listen on. * @param async If true, run messages on the transport in separate threads. * @param zip If true, zip packets on the network. This takes ~2x as much CPU, but * lowers the size of packets sent. * @param allowJumboPackets If true, allow sending of "jumbo packets" (fragmented packets) larger than * the MTU of the interface. On one hand, this allows for UDP with larger packet sizes; * on the other hand, this may be unstable / slower on the open internet, vs a known * local area network. * * @throws UnknownHostException Thrown if we could not get our own hostname. */ private UDPTransport(int udpListenPort, int tcpListenPort, boolean async, boolean zip, boolean allowJumboPackets) throws IOException { // I. Save some trivial variables this.udpListenPort = udpListenPort; this.tcpListenPort = tcpListenPort; this.serverName = InetAddress.getLocalHost(); this.serverAddress = this.serverName.getHostAddress(); this.socket = new DatagramSocket(); this.socket.setSendBufferSize(MAX_UDP_PACKET_SIZE); this.socket.setReceiveBufferSize(MAX_UDP_PACKET_SIZE); this.serverSocket = new DatagramSocket(udpListenPort); this.thread = async; this.zip = zip; this.allowJumboPackets = allowJumboPackets; // II. Determine our broadcast address InetAddress broadcastAddr = null; Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); int minMtu = MAX_UDP_PACKET_SIZE; while (en.hasMoreElements()) { NetworkInterface ni = en.nextElement(); if (ni.isUp() && !ni.isLoopback()) { List<InterfaceAddress> list = ni.getInterfaceAddresses(); if (!list.isEmpty()) { int mtu = ni.getMTU() - 20; // 20 bytes reserved for UDP header if (mtu < minMtu) { minMtu = mtu; } } for (InterfaceAddress ia : list) { if (ia.getBroadcast() != null) { broadcastAddr = ia.getBroadcast(); log.info("Found broadcast address: {}", ia.getBroadcast()); } } } } this.mtu = minMtu; log.info("Setting MTU to {}", this.mtu); if (broadcastAddr != null && !broadcastAddr.getHostAddress().equals("0.0.0.0")) { // Case: we have a broadcast address log.info("Using real broadcast address to broadcast"); this.broadcastAddrs = new InetAddress[]{ broadcastAddr }; this.isRealBroadcast = true; } else { // Case: we need to infer the address from Kubernetes log.info("Using Kubernetes state to broadcast"); this.isRealBroadcast = false; this.broadcastAddrs = readKubernetesState(); RaftLifecycle.global.timer.get().scheduleAtFixedRate(new SafeTimerTask() { // occasionally /** {@inheritDoc} */ @Override public void runUnsafe() throws Throwable { // Get new broadcast addresses InetAddress[] oldAddrs = broadcastAddrs; broadcastAddrs = Arrays.stream(readKubernetesState()) .filter(x -> { try { return x.isReachable(100); // actually check if the addresses are reachable } catch (IOException e) { return false; } }) .toArray(InetAddress[]::new); if (broadcastAddrs.length == 0) { log.warn("Could not read Kubernetes configuration (no nodes present)"); broadcastAddrs = oldAddrs; } if (!Arrays.equals(oldAddrs, broadcastAddrs)) { log.info("detected change in online nodes: {} (from {})", StringUtils.join(broadcastAddrs, ","), StringUtils.join(oldAddrs, ",")); } // Force refresh our sockets for (InetAddress addr : broadcastAddrs) { getTcpSocket(addr, true); } // Broadcast a ping broadcastTransport(UDPBroadcastProtos.MessageType.PING, UDPTransport.this.serverName.getAddress()); } }, Duration.ofSeconds(10), Duration.ofSeconds(10)); } log.info("Broadcast addresses are [{}] (is_inferred={})", StringUtils.join(this.broadcastAddrs, ", "), broadcastAddr != null); if (this.isRealBroadcast) { this.socket.setBroadcast(true); } this.socket.setTrafficClass(0x10); // IPTOS_LOWDELAY // III. Configure thread for UDP listener log.info("Binding UDP to " + udpListenPort); Thread reader = new Thread(() -> { try { byte[] recvBuffer = new byte[MAX_UDP_PACKET_SIZE]; DatagramPacket packet = new DatagramPacket(recvBuffer, recvBuffer.length); log.info("Started UDP listener thread"); //noinspection InfiniteLoopStatement while (true) { try { // 1. Receive the packet if (serverSocket.isClosed()) { log.info("UDP socket was closed -- reopening"); this.serverSocket = new DatagramSocket(udpListenPort); } serverSocket.receive(packet); Object prometheusBegin = Prometheus.startTimer(summaryTimer, "parse_upd_packet"); // 2. Parse the packet byte[] datagram = new byte[packet.getLength()]; System.arraycopy(packet.getData(), packet.getOffset(), datagram, 0, datagram.length); byte[] protoBytes; if (this.zip) { try { protoBytes = ZipUtils.gunzip(datagram); } catch (Throwable t) { protoBytes = datagram; // fall back on unzipped bytes } } else { protoBytes = datagram; } UDPBroadcastProtos.UDPPacket proto = UDPBroadcastProtos.UDPPacket.parseFrom(protoBytes); if (proto == null) { continue; } Prometheus.observeDuration(prometheusBegin); // 3. Notify listeners if (proto.getType() == UDPBroadcastProtos.MessageType.PING) { this.pingsReceived.put(proto.getContents().toByteArray(), System.currentTimeMillis()); } else if (!proto.getIsBroadcast() || !proto.getSender().equals(this.serverAddress)){ IdentityHashSet<Consumer<byte[]>> listeners; synchronized (this.listeners) { listeners = this.listeners.get(proto.getType()); } if (listeners != null) { for (Consumer<byte[]> listener : listeners) { doAction(async, "inbound message of type " + proto.getType(), () -> listener.accept(proto.getContents().toByteArray())); } } } } catch (IOException e) { log.warn("IOException receiving packet from UDP: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } catch (Throwable t) { log.warn("Caught throwable in UDP RPC receive method with packet length "+packet.getLength()+" (at offset "+packet.getOffset()+" in the buffer of size "+packet.getData().length+") and with source "+packet.getAddress()+": ", t); } finally { lastMessageReceived = System.currentTimeMillis(); } } } finally { log.error("Why did we shut down the transport listener thread?"); } }); // Start the thread reader.setDaemon(true); reader.setName("udp-listener"); reader.setUncaughtExceptionHandler((t, e) -> log.warn("Uncaught exception on thread {}: ", t, e)); reader.setPriority(Thread.MAX_PRIORITY - 1); reader.start(); // IV. Configure thread for TCP listener log.info("Binding TCP to " + tcpListenPort); Thread tcpServer = new Thread(() -> { try { ServerSocket sock = new ServerSocket(tcpListenPort); log.info("Started TCP listener thread"); //noinspection InfiniteLoopStatement while (true) { // 1. Accept the client try { Socket client = sock.accept(); Thread clientReader = new Thread(() -> { try { UDPBroadcastProtos.UDPPacket proto; // 2. Receive the packets // If the client is closed, stop listening while (!client.isClosed()) { proto = UDPBroadcastProtos.UDPPacket.parseDelimitedFrom(client.getInputStream()); // If no proto left to read, close the listener. Otherwise, we may infinite loop if (proto == null) { break; } // 3. Notify listeners Object prometheusBegin = Prometheus.startTimer(summaryTimer, "parse_tcp_packet"); IdentityHashSet<Consumer<byte[]>> listeners; synchronized (this.listeners) { listeners = new IdentityHashSet<>(this.listeners.get(proto.getType())); // copy, to prevent concurrency bugs } final byte[] bytes = proto.getContents().toByteArray(); Prometheus.observeDuration(prometheusBegin); for (Consumer<byte[]> listener : listeners) { doAction(async, "inbound TCP message of type " + proto.getType(), () -> listener.accept(bytes)); } } } catch (IOException e) { log.warn("IOException receiving packet from TCP: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } catch (Throwable t) { log.warn("Caught throwable in TCP RPC receive method: ", t); } finally { lastMessageReceived = System.currentTimeMillis(); try { client.close(); } catch (IOException e) { log.warn("Could not close TCP socket: ", e); } } }); // 4. Start the thread clientReader.setDaemon(true); clientReader.setName("tcp-listener-"+ client.getInetAddress().getHostName()); clientReader.setUncaughtExceptionHandler((t, e) -> log.warn("Uncaught exception on {}: ", t, e)); clientReader.setPriority(Math.max(Thread.NORM_PRIORITY, Thread.MAX_PRIORITY - 1)); clientReader.start(); } catch (IOException e) { log.warn("IOException receiving new socket on TCP: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } catch (Throwable t) { log.warn("Caught throwable in TCP receive method: ", t); } finally { lastMessageReceived = System.currentTimeMillis(); } } } catch (Throwable e) { log.error("Could not establish TCP socket -- this is an error!"); } finally { log.error("Why did we shut down the transport listener thread?"); } }); // Start the thread tcpServer.setDaemon(true); tcpServer.setName("tcp-listener"); tcpServer.setUncaughtExceptionHandler((t, e) -> log.warn("Uncaught exception on thread {}: ", t, e)); tcpServer.setPriority(Thread.MAX_PRIORITY - 1); tcpServer.start(); // V. Configure sender thread log.info("Starting sender thread" + tcpListenPort); final AtomicLong lastSendTime = new AtomicLong(-1L); // This thread waits for messages to show up on a send queue, and sends // them one by one. The motivation here is to allow the thread to be // interrupted by the timer task below if a message takes too long to send. Thread sender = new Thread(() -> { //noinspection InfiniteLoopStatement while (true) { try { // 1. Wait for a message synchronized (sendQueue) { while (sendQueue.isEmpty()) { try { sendQueue.wait(100); } catch (InterruptedException ignored) {} } } // 2. Get the message Runnable message = sendQueue.poll(); try { // 3. Send the message if (message != null) { lastSendTime.set(System.currentTimeMillis()); message.run(); lastSendTime.set(-1L); } } catch (Exception e) { log.warn("Could not send message: {}: {}", e.getClass().getSimpleName(), e.getMessage()); } } catch (Throwable t) { log.warn("Caught exception sending message on transport: ", t); } } }); sender.setDaemon(true); sender.setName("transport-sender"); sender.setUncaughtExceptionHandler((t, e) -> log.warn("Uncaught exception on thread {}: ", t, e)); sender.setPriority(Thread.MAX_PRIORITY - 1); sender.start(); // Every 100ms, make sure that the socket sender thread is not stuck. RaftLifecycle.global.timer.get().scheduleAtFixedRate(new SafeTimerTask() { @Override public void runUnsafe() { if (System.currentTimeMillis() - lastSendTime.get() > 100) { sender.interrupt(); } } }, Duration.ofMillis(100)); } /** @see #UDPTransport(int, int, boolean, boolean, boolean) */ public UDPTransport() throws IOException { this(DEFAULT_UDP_LISTEN_PORT, DEFAULT_TCP_LISTEN_PORT, false, false, false); } /** * Read the Kubernetes broadcast state from a file. * * @return The addresses of all the nodes known to Kubernetes. * * @throws IOException Thrown if we could not read the Kubernetes state. */ public static InetAddress[] readKubernetesState() throws IOException { String path = System.getenv("ELOQUENT_RAFT_MEMBERS"); if (path == null || "".equals(path)) { throw new FileNotFoundException("Could not find Kubernetes file variable ELOQUENT_RAFT_MEMBERS"); } String[] entries = IOUtils.slurpReader(IOUtils.readerFromString(path)).split("\n"); return Arrays.stream(entries) .filter(x -> x.trim().length() > 0) .map(x -> x.split("\\t|\\s{2,}")) // split on tabs, or on 2 (or more) spaces .filter(x -> x.length > 0 && IP_REGEX.matcher(x[0]).matches()) .map((String[] x) -> { try { return InetAddress.getByName(x[0]); } catch (UnknownHostException e) { log.warn("Unknown host: " + x[0]); return null; } }).filter(Objects::nonNull) .toArray(InetAddress[]::new); } /** {@inheritDoc} */ public void bind(UDPBroadcastProtos.MessageType channel, Consumer<byte[]> listener) { synchronized (this.listeners) { IdentityHashSet<Consumer<byte[]>> listenersOnChannel = this.listeners.computeIfAbsent(channel, k -> new IdentityHashSet<>()); listenersOnChannel.add(listener); } } /** * Send a message over the transport to a destination. * * @param destination The destination we're sending to. * @param messageType The type of message we're sending. * @param message The message we're sending. * * @return True if the message was sent; false if the message was too long. */ public boolean sendTransport(String destination, UDPBroadcastProtos.MessageType messageType, byte[] message) { try { // 1. Create the packet UDPBroadcastProtos.UDPPacket proto = UDPBroadcastProtos.UDPPacket.newBuilder() .setIsBroadcast(false) .setType(messageType) .setSender(this.serverAddress) .setContents(ByteString.copyFrom(message)) .build(); byte[] datagram = this.zip ? ZipUtils.gzip(proto.toByteArray()) : proto.toByteArray(); // 2. Send the packet if ( (this.allowJumboPackets && datagram.length < MAX_UDP_PACKET_SIZE) || (!this.allowJumboPackets && datagram.length < this.mtu) ) { // 2.A. Send over UDP // 2.1. Copy the packet into the UDP buffer DatagramPacket packet = new DatagramPacket(datagram, datagram.length, InetAddress.getByName(destination), udpListenPort); // 2.2. Reconnect if necessary if (this.socket.isClosed()) { synchronized (this) { if (this.socket.isClosed()) { log.info("UDP socket was closed (in send call) -- reopening"); this.socket = new DatagramSocket(); this.socket.setSendBufferSize(MAX_UDP_PACKET_SIZE); if (this.isRealBroadcast) { this.socket.setBroadcast(true); } this.socket.setTrafficClass(0x10); // IPTOS_LOWDELAY } } } // 2.3. Send the packet long socketSendStart = System.currentTimeMillis(); try { this.socket.send(packet); } finally { long socketSendEnd = System.currentTimeMillis(); if (socketSendEnd > socketSendStart + 10) { log.warn("Sending a direct message on the UDP socket took {}", TimerUtils.formatTimeDifference(socketSendEnd - socketSendStart)); } } if (networkSeemsDown) { log.info("Network is back up"); } networkSeemsDown = false; // 3. Return return true; } else { // 2.B. Send over TCP log.debug("Message is too long to send as a single packet ({}); sending over TCP", datagram.length); Optional<Socket> tcpSocket = getTcpSocket(InetAddress.getByName(destination), false); tcpSocket.ifPresent(socket1 -> safeWrite(proto, socket1, "sendTransport")); } } catch (SocketException e) { log.warn("Could not create datagram socket: ", e); } catch (UnknownHostException e) { log.warn("No such destination: ", e); } catch (IOException e) { if (e.getMessage() != null && (e.getMessage().equals("Network is unreachable") || e.getMessage().equals("Network is down"))) { if (!networkSeemsDown) { log.warn("Network seems to have disconnected! UDPTransport is not sending messages"); } networkSeemsDown = true; } else { log.warn("Could not send message on datagram socket: ", e); } } finally { lastMessageSent = System.currentTimeMillis(); } return false; } /** * A cache for open TCP sockets to various endpoints. */ final Map<InetAddress, Socket> tcpSocketCache = new HashMap<>(); /** * Gets a cached TCP socket to a box. * Note that this method can be slow -- up to 100ms -- in the case that * the receiving socket is not playing nice and does not complete the handshake * in a timely fashion. * * @param addr The address we're connecting to * @param forceRetry If true, force trying to reconnect to the socket. */ private Optional<Socket> getTcpSocket(InetAddress addr, boolean forceRetry) { Socket candidate; synchronized (tcpSocketCache) { if ((candidate = tcpSocketCache.get(addr)) == null && !forceRetry && tcpSocketCache.containsKey(addr)) { // we've explicitly null'd this socket return Optional.empty(); } } if (candidate == null || candidate.isClosed()) { // This socket doesn't exist, or is closed // 1. Check that the address is even alive try { if (!addr.isReachable(100)) { synchronized (tcpSocketCache) { tcpSocketCache.put(addr, null); } log.warn("{} is reachable: ", addr); return Optional.empty(); } } catch (IOException e) { log.warn("Could not check if {} is reachable: ", addr, e); synchronized (tcpSocketCache) { tcpSocketCache.put(addr, null); } return Optional.empty(); } // 2. Get the socket on a killable thread final CompletableFuture<Socket> asyncSocket = new CompletableFuture<>(); Thread tcpGetter = new Thread( () -> { try { Socket impl = new Socket(addr, tcpListenPort); synchronized (asyncSocket) { asyncSocket.complete(impl); } } catch (IOException e) { asyncSocket.completeExceptionally(e); } }); tcpGetter.setName("socket-creator-" + addr.getHostAddress()); tcpGetter.setDaemon(true); tcpGetter.setUncaughtExceptionHandler((t, e) -> log.warn("Uncaught exception on {}: ", t, e)); tcpGetter.start(); // 3. Wait on the result of the thread try { candidate = asyncSocket.get(5, TimeUnit.SECONDS); // a socket connection to Google from my home wifi takes 20ms // 4. Set the socket synchronized (tcpSocketCache) { Socket mostRecent = tcpSocketCache.get(addr); if (mostRecent != null && !mostRecent.isClosed()) { try { candidate.close(); // we encountered a race condition -- close our newer socket } catch (IOException ignored) {} } else { tcpSocketCache.put(addr, candidate); // we have a new socket } } log.info("refreshed TCP socket for {}", addr); } catch (ExecutionException | InterruptedException | TimeoutException e) { log.warn("Could not create TCP socket to {} -- exception on future: ", addr, e); return Optional.empty(); } finally { if (tcpGetter.isAlive()) { // kill the thread tcpGetter.interrupt(); } } } // 5. Return return Optional.of(candidate); } /** * Send the given message to everyone on the network. * * @param messageType The type of message we're sending. * @param message The messge to send */ public boolean broadcastTransport(UDPBroadcastProtos.MessageType messageType, byte[] message) { long startTime = System.currentTimeMillis(); try { // 1. Create the packet UDPBroadcastProtos.UDPPacket proto = UDPBroadcastProtos.UDPPacket.newBuilder() .setIsBroadcast(true) .setType(messageType) .setSender(this.serverAddress) .setContents(ByteString.copyFrom(message)) .build(); byte[] datagram = this.zip ? ZipUtils.gzip(proto.toByteArray()) : proto.toByteArray(); // 2. Broadcast the packet boolean allSuccess = true; if ( (this.allowJumboPackets && datagram.length < MAX_UDP_PACKET_SIZE) || (!this.allowJumboPackets && datagram.length < this.mtu) ) { // 2.A. The packet is small enough to go over UDP // 2.1. For each address in the broadcast... for (InetAddress broadcastAddr : this.broadcastAddrs) { long sendStart = System.currentTimeMillis(); try { // 2.2. If it's not ourselves... if (!broadcastAddr.equals(this.serverName)) { // 2.3. Copy the packet into the UDP buffer DatagramPacket packet = new DatagramPacket(datagram, datagram.length, broadcastAddr, udpListenPort); // 2.4. Reconnect the socket if necessary if (this.socket.isClosed()) { synchronized (this) { if (this.socket.isClosed()) { log.info("UDP socket was closed (in broadcast call) -- reopening"); this.socket = new DatagramSocket(); this.socket.setSendBufferSize(MAX_UDP_PACKET_SIZE); if (this.isRealBroadcast) { this.socket.setBroadcast(true); } this.socket.setTrafficClass(0x10); // IPTOS_LOWDELAY } } } // 2.5. Send the packet long socketSendStart = System.currentTimeMillis(); try { this.socket.send(packet); } finally { long socketSendEnd = System.currentTimeMillis(); if (socketSendEnd > socketSendStart + 10) { log.warn("Sending a broadcast to {} on the UDP socket took {} for packet of length {}", broadcastAddr, TimerUtils.formatTimeDifference(socketSendEnd - socketSendStart), packet.getLength()); } } if (networkSeemsDown) { log.info("Network is back up"); } networkSeemsDown = false; } } catch (Throwable t) { // Case: we could not send a packet -- don't give up, but mark the failure allSuccess = false; if (t.getMessage() != null && (t.getMessage().equals("Network is unreachable") || t.getMessage().equals("Network is down"))) { if (!networkSeemsDown) { log.warn("Network seems to have disconnected! UDPTransport is not sending messages"); } networkSeemsDown = true; } else { log.warn("Could not broadcast to " + broadcastAddr + " (attempt took " + TimerUtils.formatTimeSince(sendStart) + ") -- still trying other addressed", t); } } finally { long sendEnd = System.currentTimeMillis(); if (sendEnd > sendStart + 10) { log.warn("Sending broadcast to {} on transport took {}", broadcastAddr, TimerUtils.formatTimeDifference(sendEnd - sendStart)); } } } // 3. Return return allSuccess; } else if (!this.isRealBroadcast) { // 2.B. Send over TCP log.debug("Message is too long to send as a single packet ({}) -- broadcasting over TCP", datagram.length); // 2.1. For each address in the broadcast... for (InetAddress addr : this.broadcastAddrs) { try { Optional<Socket> tcpSocket = getTcpSocket(addr, false); tcpSocket.ifPresent(socket1 -> safeWrite(proto, socket1, "broadcastTransport")); } catch (Throwable t) { log.warn("Unhandled exception sending message on TCP socket", t); } } } else { log.debug("Message is too long to send as a single packet ({}), and we only have a broadcast address", datagram.length); } } finally { lastMessageSent = System.currentTimeMillis(); log.trace("Sending UDP broadcast took {}", TimerUtils.formatTimeSince(startTime)); } return false; } /** * Write a message to a TCP socket, handling the associated errors gracefully. * This method is not guaranteed to write the packet, but is guaranteed to not exception. * * @param proto The message we want to send over the socket. * @param tcpSocket The socket we're sending the message over * @param source A debug source for when we log errors. */ private void safeWrite(UDPBroadcastProtos.UDPPacket proto, Socket tcpSocket, String source) { synchronized (sendQueue) { if (sendQueue.size() < 10000) { sendQueue.offer(() -> { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (tcpSocket) { try { proto.writeDelimitedTo(tcpSocket.getOutputStream()); } catch (IOException e) { log.info("IO or Socket exception writing to TCP socket ({}): {}", source, e.getMessage()); try { tcpSocket.close(); } catch (Throwable ignored) { } } catch (Throwable e) { log.warn("Unknown exception writing to TCP socket (" + source + "): ", e); } } }); sendQueue.notify(); } } } /** * Get the set of servers which have been responding to ping requests in the last * threshold ms * * @param pingThreshold The threshold under which to consider a server alive. * * @return The set of servers alive within that threshold. */ private Set<String> liveServers(@SuppressWarnings("SameParameterValue") long pingThreshold) { Set<String> servers = new HashSet<>(); for (Map.Entry<byte[], Long> entry : this.pingsReceived.entrySet()) { if (Math.abs(entry.getValue() - System.currentTimeMillis()) < pingThreshold) { List<String> ipElem = new ArrayList<>(); for (byte b : entry.getKey()) { ipElem.add(Integer.toString((((int) b) + 256) % 256)); } servers.add(StringUtils.join(ipElem, ".")); } } return servers; } /** {@inheritDoc} */ @Override public String toString() { return "UDP@" + SystemUtils.HOST + " (" + this.serverAddress + ")" + " <last message sent " + TimerUtils.formatTimeSince(lastMessageSent) + " ago; received " + TimerUtils.formatTimeSince(lastMessageReceived) + " ago>" + " <broadcasting to " + Arrays.asList(this.broadcastAddrs) + ">" + " <pings from " + StringUtils.join(liveServers(60000), ", ") + ">" ; } /** * The default UDP broadcast. */ public static Lazy<Transport> DEFAULT = Lazy.of(() -> { try { return new UDPTransport(); } catch (IOException e) { log.warn("UDPTransport already bound to address! Returning mock implementation"); return new Transport(){ /** {@inheritDoc} */ @Override public void bind(UDPBroadcastProtos.MessageType channel, Consumer<byte[]> listener) { log.warn("UDP address is in use: cannot bind to transport"); } /** {@inheritDoc} */ @Override public boolean sendTransport(String destination, UDPBroadcastProtos.MessageType messageType, byte[] message) { log.warn("UDP address is in use: cannot send on transport"); return false; } /** {@inheritDoc} */ @Override public boolean broadcastTransport(UDPBroadcastProtos.MessageType messageType, byte[] message) { log.warn("UDP address is in use: cannot broadcast on transport"); return false; } }; } }); public static void main(String[] args) throws IOException { new UDPTransport(); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/error/RaftErrorListener.java
package ai.eloquent.error; /** * An error listener, for when something goes wrong in Raft. */ @FunctionalInterface public interface RaftErrorListener { /** * Register than an error has occurred in Raft. * * @param incidentKey A unique key for the incident type. * @param debugMessage A more detailed debug message for the incident. * @param stackTrace The stack trace of the incident. */ void accept(String incidentKey, String debugMessage, StackTraceElement[] stackTrace); }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/io/IOUtils.java
package ai.eloquent.io; import ai.eloquent.util.RuntimeIOException; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Helper Class for various I/O related things. */ public class IOUtils { private static final int SLURP_BUFFER_SIZE = 16384; // A class of static methods private IOUtils() { } /** * Open a BufferedReader to a file, class path entry or URL specified by a String name. * If the String starts with https?://, then it is first tried as a URL. It * is next tried as a resource on the CLASSPATH, and then it is tried * as a local file. Finally, it is then tried again in case it is some network-available * file accessible by URL. If the String ends in .gz, it * is interpreted as a gzipped file (and uncompressed). The file is then * interpreted as a utf-8 text file. * Note that this method uses the ClassLoader methods, so that classpath resources must be specified as * absolute resource paths without a leading "/". * * @param textFileOrUrl What to read from * @return The BufferedReader * @throws IOException If there is an I/O problem */ public static BufferedReader readerFromString(String textFileOrUrl) throws IOException { return new BufferedReader(new InputStreamReader( getInputStreamFromURLOrClasspathOrFileSystem(textFileOrUrl), "UTF-8")); } /** * Open a BufferedReader to a file or URL specified by a String name. If the * String starts with https?://, then it is first tried as a URL, otherwise it * is next tried as a resource on the CLASSPATH, and then finally it is tried * as a local file or other network-available file . If the String ends in .gz, it * is interpreted as a gzipped file (and uncompressed), else it is interpreted as * a regular text file in the given encoding. * If the encoding passed in is null, then the system default encoding is used. * * @param textFileOrUrl What to read from * @param encoding CharSet encoding. Maybe be null, in which case the * platform default encoding is used * @return The BufferedReader * @throws IOException If there is an I/O problem */ public static BufferedReader readerFromString(String textFileOrUrl, String encoding) throws IOException { InputStream is = getInputStreamFromURLOrClasspathOrFileSystem(textFileOrUrl); if (encoding == null) { return new BufferedReader(new InputStreamReader(is)); } return new BufferedReader(new InputStreamReader(is, encoding)); } /** * Returns all the text from the given Reader. * Closes the Reader when done. * * @return The text in the file. */ public static String slurpReader(Reader reader) { StringBuilder buff = new StringBuilder(); try (BufferedReader r = new BufferedReader(reader)) { char[] chars = new char[SLURP_BUFFER_SIZE]; while (true) { int amountRead = r.read(chars, 0, SLURP_BUFFER_SIZE); if (amountRead < 0) { break; } buff.append(chars, 0, amountRead); } } catch (Exception e) { throw new RuntimeIOException("slurpReader IO problem", e); } return buff.toString(); } /** * Locates this file either using the given URL, or in the CLASSPATH, or in the file system * The CLASSPATH takes priority over the file system! * This stream is buffered and gunzipped (if necessary). * * @param textFileOrUrl The String specifying the URL/resource/file to load * @return An InputStream for loading a resource * @throws IOException On any IO error * @throws NullPointerException Input parameter is null */ public static InputStream getInputStreamFromURLOrClasspathOrFileSystem(String textFileOrUrl) throws IOException, NullPointerException { InputStream in; if (textFileOrUrl == null) { throw new NullPointerException("Attempt to open file with null name"); } else if (textFileOrUrl.matches("https?://.*")) { URL u = new URL(textFileOrUrl); URLConnection uc = u.openConnection(); in = uc.getInputStream(); } else { try { in = findStreamInClasspathOrFileSystem(textFileOrUrl); } catch (FileNotFoundException e) { try { // Maybe this happens to be some other format of URL? URL u = new URL(textFileOrUrl); URLConnection uc = u.openConnection(); in = uc.getInputStream(); } catch (IOException e2) { // Don't make the original exception a cause, since it is usually bogus throw new IOException("Unable to open \"" + textFileOrUrl + "\" as " + "class path, filename or URL"); // , e2); } } } // If it is a GZIP stream then ungzip it if (textFileOrUrl.endsWith(".gz")) { try { in = new GZIPInputStream(in); } catch (Exception e) { throw new RuntimeIOException("Resource or file looks like a gzip file, but is not: " + textFileOrUrl, e); } } // buffer this stream. even gzip streams benefit from buffering, // such as for the shift reduce parser [cdm 2016: I think this is only because default buffer is small; see below] in = new BufferedInputStream(in); return in; } /** * Locates this file either in the CLASSPATH or in the file system. The CLASSPATH takes priority. * Note that this method uses the ClassLoader methods, so that classpath resources must be specified as * absolute resource paths without a leading "/". * * @param name The file or resource name * @throws FileNotFoundException If the file does not exist * @return The InputStream of name, or null if not found */ private static InputStream findStreamInClasspathOrFileSystem(String name) throws FileNotFoundException { // ms 10-04-2010: // - even though this may look like a regular file, it may be a path inside a jar in the CLASSPATH // - check for this first. This takes precedence over the file system. InputStream is = IOUtils.class.getClassLoader().getResourceAsStream(name); // windows File.separator is \, but getting resources only works with / if (is == null) { is = IOUtils.class.getClassLoader().getResourceAsStream(name.replaceAll("\\\\", "/")); // Classpath doesn't like double slashes (e.g., /home/user//foo.txt) if (is == null) { is = IOUtils.class.getClassLoader().getResourceAsStream(name.replaceAll("\\\\", "/").replaceAll("/+", "/")); } } // if not found in the CLASSPATH, load from the file system if (is == null) { is = new FileInputStream(name); } return is; } /** * Writes a string to a file. * * @param contents The string to write * @param path The file path * @param encoding The encoding to encode in * @throws IOException In case of failure */ public static void writeStringToFile(String contents, String path, String encoding) throws IOException { OutputStream writer = getBufferedOutputStream(path); writer.write(contents.getBytes(encoding)); writer.close(); } private static OutputStream getBufferedOutputStream(String path) throws IOException { OutputStream os = new BufferedOutputStream(new FileOutputStream(path)); if (path.endsWith(".gz")) { os = new GZIPOutputStream(os); } return os; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/monitoring/Prometheus.java
package ai.eloquent.monitoring; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Objects; /** * A facade for handling calls to Prometheus * When Prometheus is not found in the classpath, or a different version is found, we revert to a mocked version of Prometheus * * We enforce that 2 metrics with the same name refer to the same metric. * Author: zameschua */ public class Prometheus { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(Prometheus.class); /** * This is a static utility class */ private Prometheus() { } /** A flag to indicate if we are using prometheus or mocking it */ private static boolean havePrometheus = false; /** Mocked gauges, in case we don't have Prometheus in our classpath */ private static final HashMap<String, Object> summaries = new HashMap<>(); /** Mocked gauges, in case we don't have Prometheus in our classpath */ private static final HashMap<String, Object> gauges = new HashMap<>(); /** Mocked counters, in case we don't have Prometheus in our classpath */ private static final HashMap<String, Object> counters = new HashMap<>(); @Nullable private static Method SUMMARY_METHOD_BUILD; @Nullable private static Method SUMMARY_METHOD_LABELS; @Nullable private static Method SUMMARY_METHOD_STARTTIMER; @Nullable private static Method SUMMARYBUILDER_METHOD_LABELNAMES; @Nullable private static Method SUMMARYBUILDER_METHOD_REGISTER; @Nullable private static Method TIMER_METHOD_OBSERVE_DURATION; @Nullable private static Method GAUGE_METHOD_BUILD; @Nullable private static Method GAUGE_METHOD_GET; @Nullable private static Method GAUGE_METHOD_SET; @Nullable private static Method GAUGE_METHOD_INC; @Nullable private static Method GAUGE_METHOD_DEC; @Nullable private static Method GAUGEBUILDER_METHOD_REGISTER; @Nullable private static Method COUNTER_METHOD_BUILD; @Nullable private static Method COUNTER_METHOD_INC; @Nullable private static Method COUNTERBUILDER_METHOD_REGISTER; static { try { Class<?> SummaryClass = Class.forName("io.prometheus.client.Summary"); Class<?> summaryChildClass = Class.forName("io.prometheus.client.Summary$Child"); Class<?> SummaryBuilderClass = Class.forName("io.prometheus.client.Summary$Builder"); Class<?> SummaryTimerClass = Class.forName("io.prometheus.client.Summary$Timer"); Class<?> GaugeClass = Class.forName("io.prometheus.client.Gauge"); Class<?> GaugeBuilderClass = Class.forName("io.prometheus.client.Gauge$Builder"); Class<?> CounterClass = Class.forName("io.prometheus.client.Gauge"); Class<?> CounterBuilderClass = Class.forName("io.prometheus.client.Gauge$Builder"); SUMMARY_METHOD_BUILD = SummaryClass.getMethod("build", String.class, String.class); SUMMARY_METHOD_LABELS = SummaryClass.getMethod("labels", String[].class); SUMMARY_METHOD_STARTTIMER = summaryChildClass.getMethod("startTimer"); SUMMARYBUILDER_METHOD_LABELNAMES = SummaryBuilderClass.getMethod("labelNames", String[].class); SUMMARYBUILDER_METHOD_REGISTER = SummaryBuilderClass.getMethod("register"); TIMER_METHOD_OBSERVE_DURATION = SummaryTimerClass.getMethod("observeDuration"); GAUGE_METHOD_BUILD = GaugeClass.getMethod("build", String.class, String.class); GAUGE_METHOD_GET = GaugeClass.getMethod("get"); GAUGE_METHOD_SET = GaugeClass.getMethod("set", double.class); GAUGE_METHOD_INC = GaugeClass.getMethod("inc"); GAUGE_METHOD_DEC = GaugeClass.getMethod("dec"); GAUGEBUILDER_METHOD_REGISTER = GaugeBuilderClass.getMethod("register"); COUNTER_METHOD_INC = CounterClass.getMethod("inc"); COUNTER_METHOD_BUILD = CounterClass.getMethod("build", String.class, String.class); COUNTERBUILDER_METHOD_REGISTER = CounterBuilderClass.getMethod("register"); havePrometheus = true; } catch (ClassNotFoundException e) { log.info("Could not find Prometheus in your classpath -- not logging statistics", e); } catch (NoSuchMethodException e) { log.warn("Prometheus methods are not as expected (version mismatch?) -- not logging statistics", e); e.printStackTrace(); SUMMARY_METHOD_BUILD = null; SUMMARY_METHOD_STARTTIMER = null; SUMMARYBUILDER_METHOD_LABELNAMES = null; SUMMARYBUILDER_METHOD_REGISTER = null; TIMER_METHOD_OBSERVE_DURATION = null; SUMMARY_METHOD_LABELS = null; GAUGE_METHOD_BUILD = null; GAUGE_METHOD_GET = null; GAUGE_METHOD_SET = null; GAUGE_METHOD_INC = null; GAUGE_METHOD_DEC = null; GAUGEBUILDER_METHOD_REGISTER = null; COUNTER_METHOD_INC = null; COUNTER_METHOD_BUILD = null; COUNTERBUILDER_METHOD_REGISTER = null; } } /** * Clear all of our mock metrics */ static void resetMetrics() { summaries.clear(); gauges.clear(); counters.clear(); } /** * Builds and returns a new Prometheus Summary object, if possible. * * @param name The name of the metric * @param help The help string of the metric * @param labels The label to attach to the metric * * @return The Summary object */ public static Object summaryBuild(String name, String help, String... labels) { Object result; if (havePrometheus && name != null) { try { // 1a: Using Prometheus and summary does not exist yet if (!summaries.containsKey(name)) { Object builder = SUMMARY_METHOD_BUILD.invoke(null, name, help); builder = SUMMARYBUILDER_METHOD_LABELNAMES.invoke(builder, new Object[]{labels}); result = SUMMARYBUILDER_METHOD_REGISTER.invoke(builder); summaries.put(name, result); // 1b: Using Prometheus and summary already exists } else { result = summaries.get(name); } } catch (InvocationTargetException e) { if (e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { log.warn("Invocation target exception", e); return new SummaryMock(name, labels); } } catch (IllegalAccessException e) { log.warn("Prometheus methods could not be invoked (version mismatch?) -- not logging statistics", e); result = new SummaryMock(name, labels); } } else { // 2a. Guard against null name if (name == null) { log.warn("Trying to build a Summary with null name"); result = new SummaryMock(name, labels); // 2b. If we are mocking Prometheus and the Summary does not exist yet } else if (!summaries.containsKey(name) && name != null) { result = new SummaryMock(name, labels); summaries.put(name, result); // 2c: If we are mocking Prometheus and the Summary already exists } else { log.warn("Trying to build a Summary with duplicate names: ", name); result = summaries.get(name); } } return result; } /** * Start a timer on a summary metric to track a duration * Call {@link Prometheus#observeDuration(Object)} at the end of what you want to measure the duration of. * * @param summary The Summary metric to start the timer on * @param labels The labels to attach * @return the Prometheus Timer object */ public static Object startTimer(@Nullable Object summary, String... labels) { Object timerMetric; if (havePrometheus && summary != null) { try { Object timer = null; Object withLabels = SUMMARY_METHOD_LABELS.invoke(summary, new Object[]{ labels }); if (withLabels != null) { timer = SUMMARY_METHOD_STARTTIMER.invoke(withLabels); } return timer; } catch (InvocationTargetException e) { if (e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { log.warn("Invocation target exception", e); timerMetric = new TimerMock(null, labels); } } catch (IllegalArgumentException | IllegalAccessException e) { log.warn("Prometheus methods could not be invoked (version mismatch?) -- not logging statistics", e); e.printStackTrace(); //noinspection ConstantConditions timerMetric = new TimerMock(null, labels); } } else { // If we are mocking Prometheus if (summary != null && !(summary instanceof SummaryMock)) { log.error("Starting a timer on something other than a SummaryMock: {}", summary.getClass()); //noinspection ConstantConditions timerMetric = new TimerMock(null, labels); // If we are mocking Prometheus and calling startTimer on something other than a SummaryMock } else { //noinspection ConstantConditions timerMetric = new TimerMock((SummaryMock) summary, labels); } } return timerMetric; } /** * Observe duration on a Prometheus timer. * @param timer The prometheus timer. */ public static double observeDuration(@Nullable Object timer) { if (havePrometheus && timer != null) { try { Double rtn = (Double) TIMER_METHOD_OBSERVE_DURATION.invoke(timer); if (rtn == null) { return 0.; } else { return rtn; } } catch (InvocationTargetException e) { if (e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { log.warn("Invocation target exception", e); return 0.; } } catch (IllegalAccessException e) { log.warn("Prometheus methods could not be invoked (version mismatch?) -- not logging statistics", e); return 0.; } catch (IllegalArgumentException e) { log.warn("Invalid parameter supplied: {}, should be of Prometheus.Summary.Timer or TimerMock class", timer.getClass()); return 0.; } // If we are mocking Prometheus } else if (timer instanceof TimerMock) { return ((TimerMock)timer).observeDuration(); // Fallback case where we are not sure what went wrong } else { log.warn("Something probably went wrong in Prometheus#observeDuration: Expected Timer or TimerMock but received {}", timer == null ? "null" : timer.getClass()); return 0.; } } /** * Builds a new Prometheus Gauge metric, if possible. * * @param name The name of the metric * @param help The help string of the metric * * @return The Gauge object, or a mock if necessary. */ public static Object gaugeBuild(String name, String help) { Object result; if (havePrometheus) { try { // 1a. Using Prometheus and we already have a Gauge with this name yet if (gauges.containsKey(name)) { result = gauges.get(name); // 1b. Using Prometheus and don't have a Gauge with this name yet } else { Object builder = GAUGE_METHOD_BUILD.invoke(null, name, help); result = GAUGEBUILDER_METHOD_REGISTER.invoke(builder); } } catch (InvocationTargetException e) { if (e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { log.warn("Invocation target exception", e); result = new GaugeMock(name); } } catch (IllegalArgumentException | IllegalAccessException e) { log.warn("Prometheus methods could not be invoked (version mismatch?) -- not logging statistics", e); result = new GaugeMock(name); } } else { // 2a. We are mocking Prometheus and we already have a Gauge with this name if (gauges.containsKey(name)) { result = gauges.get(name); // 2b. We are mocking Prometheus and we don't have a Guage with this name yet } else { result = new GaugeMock(name); } } gauges.put(name, result); return result; } /** * Gets the current value stored in the Prometheus Gauge, if possible. * * @param gauge The instance of the gauge * * @return The value of the Gauge as a Double */ public static double gaugeGet(Object gauge) { if (havePrometheus && gauge != null) { try { Double rtn = (Double) GAUGE_METHOD_GET.invoke(gauge); if (rtn == null) { return 0.0; } else { return rtn; } } catch (InvocationTargetException e) { if (e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { log.warn("Invocation target exception", e); return 0.; } } catch (IllegalArgumentException | IllegalAccessException e) { log.warn("Prometheus methods could not be invoked (version mismatch?) -- not logging statistics", e); return 0.; } // If we are mocking Prometheus } else if (gauge instanceof GaugeMock) { return ((GaugeMock) gauge).get(); } else { log.warn("Something probably went wrong in Prometheus#gaugeGet: Expected Gauge or GaugeMock but received {}", gauge == null ? "null" : gauge.getClass()); return 0.; } } /** * Sets the Prometheus Gauge to a given value, if possible. */ public static void gaugeSet(Object gauge, double val) { if (havePrometheus && gauge != null) { try { GAUGE_METHOD_SET.invoke(gauge, val); } catch (InvocationTargetException e) { if (e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { log.warn("Invocation target exception", e); } } catch (IllegalArgumentException | IllegalAccessException e) { log.warn("Prometheus methods could not be invoked (version mismatch?) -- not logging statistics", e); } // If we are mocking Prometheus } else if (gauge instanceof GaugeMock) { ((GaugeMock) gauge).set(val); } else { log.warn("Something probably went wrong in Prometheus#gaugeSet: Expected Gauge or GaugeMock but received {}", gauge == null ? "null" : gauge.getClass()); } } /** * Increments the value in the Prometheus Gauge by 1, if possible. */ public static void gaugeInc(Object gauge) { if (havePrometheus && gauge != null) { try { GAUGE_METHOD_INC.invoke(gauge); } catch (InvocationTargetException e) { if (e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { log.warn("Invocation target exception", e); } } catch (IllegalArgumentException | IllegalAccessException e) { log.warn("Prometheus methods could not be invoked (version mismatch?) -- not logging statistics", e); } // We are mocking Prometheus } else if (gauge instanceof GaugeMock){ ((GaugeMock) gauge).inc(); } else { log.warn("Something probably went wrong in Prometheus#gaugeInc: Expected Gauge or GaugeMock but received {}", gauge == null ? "null" : gauge.getClass()); } } /** * Decrements the value in the Prometheus Gauge by 1, if possible. */ public static void gaugeDec(Object gauge) { if (havePrometheus && gauge != null) { try { GAUGE_METHOD_DEC.invoke(gauge); } catch (InvocationTargetException e) { if (e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { log.warn("Invocation target exception", e); } } catch (IllegalArgumentException | IllegalAccessException e) { log.warn("Prometheus methods could not be invoked (version mismatch?) -- not logging statistics", e); } // We are mocking Prometheus } else if (gauge instanceof GaugeMock) { ((GaugeMock) gauge).dec(); } else { log.warn("Something probably went wrong in Prometheus#gaugeDec: Expected Gauge or GaugeMock but received {}", gauge == null ? "null" : gauge.getClass()); } } /** * Builds a new Prometheus Counter metric, if possible. * @param name The name of the metric * @param help The help string of the metric * * @return The Prometheus counter, or a mock if necessary. */ public static Object counterBuild(String name, String help) { Object result; if (havePrometheus) { try { Object builder = COUNTER_METHOD_BUILD.invoke(null, name, help); result = COUNTERBUILDER_METHOD_REGISTER.invoke(builder); } catch (InvocationTargetException e) { if (e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { log.warn("Invocation target exception", e); result = new CounterMock(name); } } catch (IllegalArgumentException | IllegalAccessException e) { log.warn("Prometheus methods could not be invoked (version mismatch?) -- not logging statistics", e); result = new CounterMock(name); } // If we are mocking Prometheus } else { result = new CounterMock(name); } counters.put(name, result); return result; } /** * Increments the value in the Prometheus Counter by 1, if possible. * We never do any other operations to Counter except increment it (for now) */ public static void counterInc(Object counter) { if (havePrometheus && counter != null) { try { COUNTER_METHOD_INC.invoke(counter); } catch (InvocationTargetException e) { if (e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { log.warn("Invocation target exception", e); } } catch (IllegalArgumentException | IllegalAccessException e) { log.warn("Prometheus methods could not be invoked (version mismatch?) -- not logging statistics", e); } // If we are mocking Prometheus } else if (counter instanceof CounterMock) { ((CounterMock) counter).inc(); } else { log.warn("Something probably went wrong in Prometheus#counterInc: Expected Gauge or GaugeMock but received {}", counter == null ? "null" : counter.getClass()); } } /** * Getter method for this.havePrometheus */ public static boolean havePrometheus() { return havePrometheus; } /** * A dummy mock of a Prometheus Summary object. */ private static class SummaryMock { /** The name of the summary */ public final String name; /** The labels on the summary */ public final String[] labels; /** A straightforward constructor */ public SummaryMock(String name, String[] labels) { this.name = name; this.labels = labels; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SummaryMock that = (SummaryMock) o; return Objects.equals(name, that.name) && Arrays.equals(labels, that.labels); } /** {@inheritDoc} */ @Override public int hashCode() { int result = Objects.hash(name); result = 31 * result + Arrays.hashCode(labels); return result; } } /** * A dummy mock of a Prometheus Timer object. */ private static class TimerMock { /** The summary this timer is attached to */ public final SummaryMock summary; /** The label values on this timer */ public final String[] labels; /** The time that this timer was created */ public final long startTime; /** The straightforward constructor */ public TimerMock(SummaryMock summary, String[] labels) { this.summary = summary; if (labels == null) { labels = new String[0]; } this.labels = labels; if (summary != null && summary.labels != null && labels.length != summary.labels.length) { throw new IllegalArgumentException("Summary labels + timer label values should have the same length: " + summary.labels.length + " vs " + labels.length); } this.startTime = System.nanoTime(); } /** Returns the time (in milliseconds) elapsed since this TimerMock was created */ protected double observeDuration() { long timeNanoseconds = System.nanoTime() - this.startTime; return (double) timeNanoseconds / 1000000000.0; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TimerMock timerMock = (TimerMock) o; return Objects.equals(summary, timerMock.summary) && Arrays.equals(labels, timerMock.labels); } /** {@inheritDoc} */ @Override public int hashCode() { int result = Objects.hash(summary); result = 31 * result + Arrays.hashCode(labels); return result; } } /** * A dummy mock of a Prometheus Gauge object. */ private static class GaugeMock { /** The name of the gauge */ private final String name; /** The value stored in this Gauge **/ private double value = 0; /** A straightforward constructor */ public GaugeMock(String name) { this.name = name; } /** Gets the value of this mock */ public double get() { return this.value; } /** Sets the value of this mock */ public void set(double val) { this.value = val; } /** Increments the value of this mock */ public void inc() { this.value += 1; } /** Decrements the value of this mock */ public void dec() { this.value -= 1; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GaugeMock gaugeMock = (GaugeMock) o; return Objects.equals(name, gaugeMock.name); } /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(name); } } /** * A dummy mock of a Prometheus Counter object. */ private static class CounterMock { /** The name of the counter */ public final String name; /** The name of the counter */ private double value = 0.; /** A straightforward constructor */ public CounterMock(String name) { this.name = name; } /** Increments the value of this mock */ public void inc() { this.value += 1; } /** Decrements the value of this mock */ public void dec() { this.value -= 1; } /** Sets the value of this mock to `val`*/ public void set(double val) { this.value = val; } /** Gets the value of this mock */ public double get() { return this.value; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CounterMock that = (CounterMock) o; return Objects.equals(name, that.name); } /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(name); } } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/EloquentRaftAlgorithm.java
package ai.eloquent.raft; import ai.eloquent.monitoring.Prometheus; import ai.eloquent.raft.EloquentRaftProto.*; import ai.eloquent.util.RuntimeInterruptedException; import ai.eloquent.util.TimerUtils; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import com.sun.management.GcInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.time.Instant; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.function.Consumer; /** * The implementation of Raft, filling in the expected behavior for all of the callbacks. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ @SuppressWarnings("Duplicates") public class EloquentRaftAlgorithm implements RaftAlgorithm { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(EloquentRaftAlgorithm.class); /** * A <b>very</b> conservative timeout that defines when we consider a machine to be down. * This is used in (at least) two places: * * <ol> * <li>Timing out membership changes, in the case that it takes us longer than this amount to get to the point of * being able to add a configuration entry.</li> * <li>Removing a server from the configuration that has not been responding to heartbeats.</li> * </ol> */ public static final long MACHINE_DOWN_TIMEOUT = 30000; /** * The number of broadcasts that can happen within a heartbeat interval before * we start dropping them. * For example, setting this to 5 means that 5 broadcasts can happen every 50ms. * Setting this to 10 means that 10 broadcasts can happen every 50ms. */ private static int LEAKY_BUCKET_SIZE = 10; /** * The Raft state */ private final RaftState state; /** * The underlying transport for this raft implementation */ public final RaftTransport transport; /** * Only one add server / remove server call can be taking place at a time, so we have a single Future for * serializing these calls one after another. * * This is used exclusively in * {@link #receiveAddServerRPC(AddServerRequest, long)} and * {@link #receiveRemoveServerRPC(RemoveServerRequest, long)}, * and is not stored in the {@link RaftState} because it's only for control flow (a form of synchronization), not for keeping actual state. */ private CompletableFuture<RaftMessage> clusterMembershipFuture; // initialized in the constructor /** * The last time a cluster membership state was committed. * This is to compute the grace period for cluster mismatches to be forcefully * overwritten, and is not part of the core Raft algorithm. */ private volatile long lastClusterMembershipChange; /** * The last times we broadcast our heartbeat. * Useful for rate-limiting our messages. */ private final long[] lastBroadcastTimes = new long[LEAKY_BUCKET_SIZE + 1]; /** * The pointer for the next index in {@link #lastBroadcastTimes}. */ private volatile AtomicInteger lastBroadcastNextIndex = new AtomicInteger(0); /** * This is the lifecycle that this algorithm is associated with. This is only for mocks to use. */ private final Optional<RaftLifecycle> lifecycle; /** The ID of the thread that's meant to be driving Raft, if we have one. */ private long drivingThreadId = -1; // Disabled initially /** A means of queuing tasks on the driving thread. */ private Consumer<Runnable> drivingThreadQueue = Runnable::run; // Disabled initially /** * Create a new auto-resizing Raft algorithm. * Note that this node is initially silent -- it will not initiate elections, and is not a voting member * of its own cluster. * * @param serverName The name of this server. This <b>MUST</b> be unique within a cluster. * @param stateMachine The state machine we are running on this Raft cluster. * @param transport The underlying transport. This should match the cluster name argument. * @param targetClusterSize The target size for the Raft cluster. * @param raftStateThreadPool A pool to pass to RaftState for it to use */ public EloquentRaftAlgorithm(String serverName, RaftStateMachine stateMachine, RaftTransport transport, int targetClusterSize, ExecutorService raftStateThreadPool, Optional<RaftLifecycle> lifecycle) { this(new RaftState(serverName, stateMachine, targetClusterSize, raftStateThreadPool), transport, lifecycle); } /** * Create a new fixed-size Raft algorithm. * That is, a node that won't automatically resize -- you can still add or remove nodes * manually. * * @param serverName The name of this server. This <b>MUST</b> be unique within a cluster. * @param stateMachine The state machine we are running on this Raft cluster. * @param transport The underlying transport. This should match the cluster name argument. * @param quorum The configuration of the voting members of the cluster. The cluster will not automatically * resize. * @param raftStateThreadPool A pool to pass to RaftState for it to use */ public EloquentRaftAlgorithm(String serverName, RaftStateMachine stateMachine, RaftTransport transport, Collection<String> quorum, ExecutorService raftStateThreadPool, Optional<RaftLifecycle> lifecycle) { this(new RaftState(serverName, stateMachine, quorum, raftStateThreadPool), transport, lifecycle); } /** * A constructor for unit tests primarily, that explicitly sets the state for Raft. */ public EloquentRaftAlgorithm(RaftState state, RaftTransport transport, Optional<RaftLifecycle> lifecycle) { this.state = state; this.transport = transport; this.lifecycle = lifecycle; this.clusterMembershipFuture = CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).build()); this.lastClusterMembershipChange = transport.now(); } /** * Set the thread that should be driving Raft, for assertions */ void setDrivingThread(Consumer<Runnable> queue) { this.drivingThreadId = Thread.currentThread().getId(); this.drivingThreadQueue = queue; } /** {@inheritDoc} */ @Override public RaftState state() { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); return state.copy(); } /** {@inheritDoc} */ @Override public RaftState mutableState() { // note[gabor]: Don't do driving thread assert -- this is a mutable state anyways return state; } @Override public RaftStateMachine mutableStateMachine() { // note[gabor]: Don't do driving thread assert -- this is a mutable state anyways return state.log.stateMachine; } /** {@inheritDoc} */ @Override public long term() { return state.currentTerm; } /** {@inheritDoc} */ @Override public String serverName() { // note[gabor]: Don't do driving thread assert -- this is a final variable return state.serverName; } // // -------------------------------------------------------------------------- // APPEND ENTRIES RPC // -------------------------------------------------------------------------- // /** {@inheritDoc} */ @Override public void receiveAppendEntriesRPC(AppendEntriesRequest heartbeat, Consumer<RaftMessage> replyLeader, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "AppendEntriesRPC"; RaftMessage reply; if (heartbeat.getEntriesCount() > 0) log.trace("{} - [{}] {}; num_entries={} prevIndex={} leader={}", state.serverName, transport.now(), methodName, heartbeat.getEntriesCount(), heartbeat.getPrevLogIndex(), heartbeat.getLeaderName()); AppendEntriesReply.Builder partialReply = AppendEntriesReply.newBuilder() .setFollowerName(state.serverName); // signal our name // Step 1: Reply false if term < currentTerm if (!canPerformFollowerAction(methodName, heartbeat.getTerm(), false)) { reply = RaftTransport.mkRaftMessage(state.serverName, partialReply .setTerm(state.currentTerm) // signal the new term .setNextIndex(state.log.getLastEntryIndex() + 1) // signal the next index in the new term .setSuccess(false) // there was no update .setMissingFromQuorum(!this.state.log.latestQuorumMembers.contains(this.state.serverName)) .build()); } else { // Valid heartbeat: Reset the election timeout Optional<String> leader = state.leader; state.resetElectionTimeout(now, heartbeat.getLeaderName()); if (!leader.equals(state.leader)) { log.info("{} - {}; registered new leader={} old leader={} time={}", state.serverName, methodName, state.leader.orElse("<none>"), leader.orElse("<none>"), now); } // Step 2-4: // 2. Reply false if log doesn't contain an entry at prevLogIndex whose term matches prevLogTerm // 3. If an existing entry conflicts with the new one (same index but different terms), delete the existing // entry and all that follow it. // 4. Append any new entries not already in the log if (state.log.appendEntries(heartbeat.getPrevLogIndex(), heartbeat.getPrevLogTerm(), heartbeat.getEntriesList())) { // Case: success // (some debugging) assert state.log.getLastEntryIndex() >= heartbeat.getPrevLogIndex() + heartbeat.getEntriesCount() : "appendEntries succeeded on " + state.serverName + ", but latest log index is not caught up(!?) prevLogIndex=" + heartbeat.getPrevLogIndex() + " entryCount=" + heartbeat.getEntriesCount() +" new_lastIndex=" + state.log.getLastEntryIndex(); if (!heartbeat.getEntriesList().isEmpty()) { try { KeyValueStateMachineProto.Transition transition = KeyValueStateMachineProto.Transition.parseFrom(heartbeat.getEntriesList().get(0).getTransition()); log.trace("{} - {} Appended entry @ time={} to index {} of type {}: {}", state.serverName, methodName, now, heartbeat.getEntriesList().get(0).getIndex(), transition.getType(), transition); } catch (InvalidProtocolBufferException ignored) { } } // (update our commit index) if (state.commitIndex() < heartbeat.getLeaderCommit()) { assert state.commitIndex() <= heartbeat.getLeaderCommit() : "Leader has committed past our current index on " + state.serverName + "! commitIndex=" + state.commitIndex() + " heartbeat.commitIndex=" + heartbeat.getLeaderCommit() + " prevLogIndex=" + heartbeat.getPrevLogIndex() + " entryCount=" + heartbeat.getEntriesCount() +" new_lastIndex=" + state.log.getLastEntryIndex(); state.commitUpTo(heartbeat.getLeaderCommit(), now); } // (step down from any elections) if (state.leadership == RaftState.LeadershipStatus.LEADER) { log.warn("{} - {} Raft got an inbound heartbeat as a leader -- this is a possible split-brain. Stepping down from leadership so we can sort it out democratically.", state.serverName, methodName); state.stepDownFromElection(); } // (reply) if (heartbeat.getEntriesCount() > 0) log.trace("{} - {} replying success; term={} nextIndex={} commitIndex={}", state.serverName, methodName, state.currentTerm, state.log.getLastEntryIndex() + 1, state.commitIndex()); reply = RaftTransport.mkRaftMessage(state.serverName, partialReply .setSuccess(true) // RPC was successful .setTerm(state.currentTerm) // signal the new term .setNextIndex(state.log.getLastEntryIndex() + 1) // signal the next index in the new term .setMissingFromQuorum(!this.state.log.latestQuorumMembers.contains(this.state.serverName)) .build()); } else if (heartbeat.getEntriesCount() > 0) { // Case: failed to append //noinspection StatementWithEmptyBody if (heartbeat.getPrevLogIndex() < this.state.log.snapshot.map(snapshot -> snapshot.lastIndex).orElse(0L)) { // This is actually ok, because we can receive appends out of order and fail an append that comes before a snapshot } else { log.warn("{} - {} replying error; term={} lastIndex={} heartbeat.term={} heartbeat.prevIndex={}", state.serverName, methodName, state.currentTerm, state.log.getLastEntryIndex(), heartbeat.getTerm(), heartbeat.getPrevLogIndex()); } long requestIndex = Math.max( state.log.snapshot.map(snapshot -> snapshot.lastIndex).orElse(0L), Math.min(heartbeat.getPrevLogIndex() - 1, state.log.getLastEntryIndex()) ); reply = RaftTransport.mkRaftMessage(state.serverName, partialReply .setSuccess(false) // the update failed .setTerm(state.currentTerm) // signal the new term .setNextIndex(requestIndex) // signal the next index in the new term .setMissingFromQuorum(!this.state.log.latestQuorumMembers.contains(this.state.serverName)) .build()); } else { // Case: this heartbeat has no payload if (heartbeat.getEntriesCount() > 0) log.trace("{} - {} heartbeat has no payload; term={} nextIndex={}", state.serverName, methodName, state.currentTerm, heartbeat.getPrevLogIndex()); reply = RaftTransport.mkRaftMessage(state.serverName, partialReply .setSuccess(false) // everything went ok, but no updates .setTerm(state.currentTerm) // signal the new term .setNextIndex(state.log.getLastEntryIndex() + 1) // signal the next index in the new term .setMissingFromQuorum(!this.state.log.latestQuorumMembers.contains(this.state.serverName)) .build()); } } replyLeader.accept(reply); } /** {@inheritDoc} */ @SuppressWarnings({"ConstantConditions", "StatementWithEmptyBody"}) @Override public void receiveAppendEntriesReply(AppendEntriesReply reply, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "AppendEntriesReply"; long begin = System.currentTimeMillis(); try { log.trace("{} - [{}] {} from {}. success={} term={} nextIndex={}", state.serverName, transport.now(), methodName, reply.getFollowerName(), reply.getSuccess(), reply.getTerm(), reply.getNextIndex()); asLeader(reply.getFollowerName(), reply.getTerm(), now, () -> { assert state.isLeader() : "We should still be a leader if we process this reply"; assert reply.getTerm() == state.currentTerm : "We should be on the correct term when getting a heartbeat reply"; assert state.nextIndex.isPresent() : "We should have a nextIndex map"; if (reply.getSuccess()) { // Case: the call was successful; update nextIndex + matchIndex state.nextIndex.ifPresent(map -> map.put(reply.getFollowerName(), Math.max(map.getOrDefault(reply.getFollowerName(), 0L), reply.getNextIndex()))); state.matchIndex.ifPresent(map -> map.put(reply.getFollowerName(), Math.max(map.getOrDefault(reply.getFollowerName(), 0L), reply.getNextIndex() - 1))); // Eloquent Addition: sanity check the quorum if (reply.getMissingFromQuorum() && state.log.committedQuorumMembers.contains(reply.getFollowerName()) && state.log.latestQuorumMembers.contains(reply.getFollowerName()) && clusterMembershipFuture.isDone() && lastClusterMembershipChange + this.electionTimeoutMillisRange().end < transport.now() ) { log.warn("{} - {} detected quorum mismatch on node {}. Trying to recover, but this is an error state.", this.state.serverName, methodName, reply.getFollowerName()); receiveAddServerRPC(AddServerRequest.newBuilder() .setNewServer(reply.getFollowerName()) .addAllQuorum(state.log.latestQuorumMembers) .build(), now); } } else { // Case: the call was rejected by the client -- resend the append entries call log.trace("{} - {} from {} was rejected. resending with term={} and nextIndex={}", state.serverName, methodName, reply.getFollowerName(), reply.getTerm(), reply.getNextIndex()); long index = Math.max(0, reply.getNextIndex() - 1); if (index > 0) { Optional<LogEntry> entryAtIndex = state.log.getEntryAtIndex(index); if (entryAtIndex.isPresent()) { // Case: the entry we'd like to send is in our logs } else if (state.log.snapshot.isPresent() && index == state.log.snapshot.get().lastIndex) { // Case: the entry we'd like to send is the last entry of our snapshot } else { // Case: the follower asked for an index that we do not have -- this is a bit of an error case long match = state.matchIndex.map(map -> map.get(reply.getFollowerName())).orElse(0L); if (match >= index) { // Case: this is a message arriving out of order, and we've already snapshotted the old logs, so this is fine } else { state.matchIndex.ifPresent(map -> map.put(reply.getFollowerName(), 0L)); state.nextIndex.ifPresent(map -> map.put(reply.getFollowerName(), 0L)); log.warn("{} - {} Follower asked for an index we do not have; setting index to 0 (to trigger snapshot)", state.serverName, methodName); index = 0; // note[gabor] this used to decrement by 1 and loop on what is now 'if (index > 0)', but that loop will never succeed? } } } // Check that we're not sending a set of empty entries, cause that would cause an infinite loop Optional<List<LogEntry>> entries = state.log.getEntriesSinceInclusive(index + 1); if (!entries.isPresent() || entries.get().size() > 0) { // This handles choosing between InstallSnapshot and AppendEntries sendAppendEntries(reply.getFollowerName(), index + 1); } } }); } finally { assert checkDuration(methodName, begin, System.currentTimeMillis()); } } /** * A generalized function for both {@link #sendAppendEntries(String, long)} and {@link #rpcAppendEntries(String, long, long)}. */ private <E> E generalizedAppendEntries(long nextIndex, BiFunction<AppendEntriesRequest, InstallSnapshotRequest, E> fn) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); // The request we're sending. This does not need to be sent in a lock Optional<AppendEntriesRequest> appendEntriesRequest = Optional.empty(); Optional<InstallSnapshotRequest> snapshotRequest = Optional.empty(); // 1. Construct the broadcast Optional<List<LogEntry>> entries = state.log.getEntriesSinceInclusive(nextIndex); Optional<Long> prevEntryTerm = state.log.getPreviousEntryTerm(nextIndex - 1); if (entries.isPresent() && prevEntryTerm.isPresent()) { // 1A. We have entries to send -- send them. appendEntriesRequest = Optional.of(AppendEntriesRequest .newBuilder() .setTerm(state.currentTerm) .setLeaderName(state.serverName) .setPrevLogIndex(nextIndex - 1) .setPrevLogTerm(prevEntryTerm.get()) .addAllEntries(entries.get()) .setLeaderCommit(state.log.getCommitIndex()) .build()); log.trace("{} - sending appendEntriesRequest; logIndex={} logTerm={} # entries={}", state.serverName, nextIndex - 1, prevEntryTerm.get(), entries.get().size()); } else { // 1B. We should send a snapshot snapshotRequest = state.log.snapshot.map(snapshot -> InstallSnapshotRequest .newBuilder() .setTerm(state.currentTerm) .setLeaderName(state.serverName) .setLastIndex(snapshot.lastIndex) .setLastTerm(snapshot.lastTerm) .addAllLastConfig(snapshot.lastClusterMembership) .setData(ByteString.copyFrom(snapshot.serializedStateMachine)) .build() ); } // 2. Send the appropriate message return fn.apply(appendEntriesRequest.orElse(null), snapshotRequest.orElse(null)); } /** * Equivalent to {@link #sendAppendEntries(String, long)}, but as an RPC. * This is used when adding servers to the cluster. */ private CompletableFuture<RaftMessage> rpcAppendEntries(String target, long nextIndex, long timeout) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "AppendEntriesRPC"; return generalizedAppendEntries(nextIndex, (heartbeat, snapshot) -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (heartbeat != null) { // Case: this is a heartbeat request return transport.rpcTransportAsFuture(state.serverName, target, heartbeat, (result, exception) -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (result != null) { return result; } else { log.warn("{} - {} Failure: <{}>", state.serverName, methodName, exception == null ? "unknown error" : (exception.getClass().getName() + ": " + exception.getMessage())); return RaftTransport.mkRaftMessage(state.serverName, RaftMessage.newBuilder().setAppendEntriesReply(AppendEntriesReply.newBuilder() .setFollowerName(target) .setTerm(state.currentTerm) .setSuccess(false)).build()); } }, this.drivingThreadQueue, timeout); } else if (snapshot != null) { // Case: this is a snapshot request return transport.rpcTransportAsFuture(state.serverName, target, snapshot, (result, exception) -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (result != null) { return result; } else { log.warn("{} - {} Failure: <{}>", state.serverName, methodName, exception == null ? "unknown error" : (exception.getClass().getName() + ": " + exception.getMessage())); return RaftTransport.mkRaftMessage(state.serverName, RaftMessage.newBuilder().setInstallSnapshotReply(InstallSnapshotReply.newBuilder() .setTerm(state.currentTerm) .build())); } }, this.drivingThreadQueue, timeout); } else { log.warn("{} - We have neither log entries or a snapshot to send to {}.", state.serverName, target); return CompletableFuture.completedFuture(RaftMessage.getDefaultInstance()); } }).thenApply(message -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (message.getAppendEntriesReply() != AppendEntriesReply.getDefaultInstance()) { AppendEntriesReply reply = message.getAppendEntriesReply(); receiveAppendEntriesReply(reply, transport.now()); } else if (message.getInstallSnapshotReply() != InstallSnapshotReply.getDefaultInstance()) { InstallSnapshotReply reply = message.getInstallSnapshotReply(); receiveInstallSnapshotReply(reply, transport.now()); } return message; }); } /** {@inheritDoc} */ @Override public void sendAppendEntries(String target, long nextIndex) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); log.trace("{} - Sending appendEntries to {} with nextIndex {}", state.serverName, target, nextIndex); generalizedAppendEntries(nextIndex, (heartbeat, snapshot) -> { if (heartbeat != null) { transport.sendTransport(state.serverName, target, heartbeat); } else if (snapshot != null) { transport.sendTransport(state.serverName, target, snapshot); } else { log.warn("{} - We have neither log entries or a snapshot to send to {}.", state.serverName, target); } return null; }); } /** {@inheritDoc} */ @Override public void broadcastAppendEntries(long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); broadcastAppendEntries(now, false, false); } /** * Broadcast entries, optionally forcing at least the last element to be sent. * * @see #broadcastAppendEntries(long) */ private void broadcastAppendEntries(long now, boolean forceLastElement, boolean force) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "broadcastAppendEntries"; AppendEntriesRequest appendEntriesRequest; // The request we're sending. This does not need to be sent in a lock // 1. Rate Limit if (!force) { int broadcastsSinceLastHeartbeat = 0; for (long broadcastTime : lastBroadcastTimes) { if (broadcastTime > 0 && now > broadcastTime && (now - broadcastTime) < this.heartbeatMillis()) { // note[gabor] broadcastTime > 0 so that unit tests grounded at 0 can pass broadcastsSinceLastHeartbeat += 1; } } if (broadcastsSinceLastHeartbeat > LEAKY_BUCKET_SIZE) { // log.info("{} - {}; Rate limiting broadcasts: {}; now={}", state.serverName, methodName, Arrays.toString(lastBroadcastTimes), now); return; } } lastBroadcastTimes[lastBroadcastNextIndex.getAndIncrement() % lastBroadcastTimes.length] = now; // 2. Preconditions if (!this.state.isLeader()) { // in case we lost leadership in between log.trace("{} - {}; Not the leader", state.serverName, methodName); return; } assert state.nextIndex.isPresent() : "Running heartbeat as leader, but don't have a nextIndex defined"; // 3. Find the largest update we have to send. long findUpdateStart = System.currentTimeMillis(); long minLogIndex = Long.MAX_VALUE; long minLogTerm = Long.MAX_VALUE; List<LogEntry> argminEntries = null; if (state.nextIndex.isPresent()) { //noinspection ConstantConditions,OptionalGetWithoutIsPresent Map<String, Long> nextIndex = state.nextIndex.get(); //noinspection ConstantConditions for (String member : state.log.getQuorumMembers()) { if (!member.equals(state.serverName)) { // don't include the leader // 3.1. Make sure the member is in state's nextIndex if (!nextIndex.containsKey(member)) { long initializeNextIndex = state.log.getLastEntryIndex() + 1; nextIndex.put(member, initializeNextIndex); } // 3.2. Get the relevant term + index of this member long nextIndexForMember = nextIndex.get(member); long prevLogIndex = Math.max(0, nextIndexForMember - 1); long prevLogTerm = state.log.getPreviousEntryTerm(prevLogIndex).orElse(-1L); Optional<List<LogEntry>> entries = state.log.getEntriesSinceInclusive(nextIndexForMember); // 3.3. Update the min if (entries.isPresent()) { // Ignore nodes that need a snapshot if (prevLogTerm < minLogTerm || (prevLogTerm == minLogTerm && prevLogIndex < minLogIndex) ) { minLogTerm = prevLogTerm; minLogIndex = prevLogIndex; argminEntries = entries.get(); } } } } } checkDuration("finding update index", findUpdateStart, System.currentTimeMillis()); // 4. Handle the case that we have no updates //noinspection ConstantConditions if (minLogTerm == Long.MAX_VALUE || minLogIndex == Long.MAX_VALUE || argminEntries == null) { minLogIndex = state.log.getLastEntryIndex(); minLogTerm = state.log.getLastEntryTerm(); argminEntries = Collections.emptyList(); if (forceLastElement && minLogIndex > 0) { // if we're forcing an update minLogIndex -= 1; minLogTerm = state.log.getPreviousEntryTerm(minLogIndex).orElse(-1L); argminEntries = state.log.getEntriesSinceInclusive(minLogIndex + 1).orElse(Collections.emptyList()); } } // 5. Update invariants if (state.isLeader()) { updateLeaderInvariantsPostMessage(Optional.empty(), now); } // 6. Construct the broadcast long constructProtoStart = System.currentTimeMillis(); appendEntriesRequest = AppendEntriesRequest .newBuilder() .setTerm(state.currentTerm) .setLeaderName(state.serverName) .setPrevLogIndex(minLogIndex) .setPrevLogTerm(minLogTerm) .addAllEntries(argminEntries) .setLeaderCommit(state.log.getCommitIndex()) .build(); checkDuration("creating heartbeat proto", constructProtoStart, System.currentTimeMillis()); // 7. Send the broadcast // 7.1. (log the broadcast while in a lock) log.trace("{} - Broadcasting appendEntriesRequest; logIndex={} logTerm={} # entries={}", state.serverName, minLogIndex, minLogTerm, argminEntries.size()); // 7.2. (the sending does not need to be locked) long broadcastStart = System.currentTimeMillis(); try { transport.broadcastTransport(state.serverName, appendEntriesRequest); } finally { checkDuration("broadcast transport call", broadcastStart, System.currentTimeMillis()); } } // // -------------------------------------------------------------------------- // INSTALL SNAPSHOT RPC // -------------------------------------------------------------------------- // /** {@inheritDoc} */ @Override public void receiveInstallSnapshotRPC(InstallSnapshotRequest snapshot, Consumer<RaftMessage> replyLeader, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "InstallSnapshotRPC"; RaftMessage reply; log.trace("{} - [{}] {}: term={} lastIndex={}", state.serverName, transport.now(), methodName, snapshot.getTerm(), snapshot.getLastIndex()); InstallSnapshotReply.Builder partialReply = InstallSnapshotReply.newBuilder() .setFollowerName(state.serverName); // Reset the election timeout Optional<String> leader = state.leader; state.resetElectionTimeout(now, snapshot.getLeaderName()); if (!leader.equals(state.leader)) { log.info("{} - {}; registered new leader={} old leader={} term={} lastIndex={} time={}", state.serverName, methodName, state.leader.orElse("<none>"), leader.orElse("<none>"), snapshot.getTerm(), snapshot.getLastIndex(), now); } // Step 1: Reply false if term < currentTerm if (!canPerformFollowerAction(methodName, snapshot.getTerm(), false)) { reply = RaftTransport.mkRaftMessage(state.serverName, partialReply .setTerm(state.currentTerm) // signal our term .setNextIndex(state.log.getLastEntryIndex() + 1) // signal our last log index .build()); } else { assert snapshot.getTerm() == state.currentTerm : "Should not have been allowed to continue if the terms don't match!"; // Step 2: Create new snapshot file RaftLog.Snapshot requestedSnapshot = new RaftLog.Snapshot( snapshot.getData().toByteArray(), snapshot.getLastIndex(), snapshot.getLastTerm(), snapshot.getLastConfigList()); // Step 3 - 8: Write data into snapshot file + save the snapshot file. If exsiting log entry has same index // and term as lastIndex and lastTerm, discard log up through lastIndex (but retain any following // entries) and reply. Discard entire log. Reset state machine using snapshot contents. state.log.installSnapshot(requestedSnapshot, now); // Reply log.trace("{} - {} success: last index in log is {}", state.serverName, methodName, state.log.getLastEntryIndex()); reply = RaftTransport.mkRaftMessage(state.serverName, partialReply .setTerm(state.currentTerm) // signal our term .setNextIndex(state.log.getLastEntryIndex() + 1) // signal our last log index .build()); } replyLeader.accept(reply); } /** {@inheritDoc} */ @Override public void receiveInstallSnapshotReply(InstallSnapshotReply reply, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "InstallSnapshotReply"; log.trace("{} - [{}] {} from {}. term={} nextIndex={}", state.serverName, transport.now(), methodName, reply.getFollowerName(), reply.getTerm(), reply.getNextIndex()); asLeader(reply.getFollowerName(), reply.getTerm(), now, () -> { // As an efficiency boost, update nextIndex and matchIndex // This is, strictly speaking, optional, as the next heartbeat will handle this automatically state.nextIndex.ifPresent(map -> map.compute(reply.getFollowerName(), (k, v) -> reply.getNextIndex())); state.matchIndex.ifPresent(map -> map.compute(reply.getFollowerName(), (k, v) -> reply.getNextIndex() - 1)); // Always send any updates immediately, if the other endpoint is behind us // Check that we're not sending a set of empty entries, cause that would cause an infinite loop Optional<List<LogEntry>> entries = state.log.getEntriesSinceInclusive(reply.getNextIndex()); if (!entries.isPresent() || entries.get().size() > 0) { // This handles choosing between InstallSnapshot and AppendEntries sendAppendEntries(reply.getFollowerName(), reply.getNextIndex()); } }); } // // -------------------------------------------------------------------------- // ELECTIONS // -------------------------------------------------------------------------- // /** {@inheritDoc} */ @Override public void receiveRequestVoteRPC(RequestVoteRequest voteRequest, Consumer<RaftMessage> replyLeader, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); // if (!alive) { return; } // Always vote -- we may need the vote on handoff String methodName = "RequestVoteRPC"; RaftMessage reply; log.trace("{} - [{}] {}; candidate={} term={}", state.serverName, transport.now(), methodName, voteRequest.getCandidateName(), voteRequest.getTerm()); if (canPerformFollowerAction(methodName, voteRequest.getTerm(), false)) { // 1. Resolve who to vote for boolean voteGranted; if (voteRequest.getTerm() < state.currentTerm) { voteGranted = false; } else { voteGranted = ( (!state.votedFor.isPresent() || state.votedFor.get().equals(voteRequest.getCandidateName())) && voteRequest.getLastLogIndex() >= state.log.getLastEntryIndex() ); if (voteGranted) { Optional<String> leader = state.leader; state.voteFor(voteRequest.getCandidateName()); if (!leader.equals(state.leader)) { log.info("{} - {}; registered new leader={} old leader={} time={}", state.serverName, methodName, state.leader.orElse("<none>"), leader.orElse("<none>"), now); } } } // 2. Respond log.trace("{} - {} replying; candidate={} vote_granted={} term={} voted_for={}", state.serverName, methodName, voteRequest.getCandidateName(), voteGranted, state.currentTerm, state.votedFor.orElse("<nobody>")); reply = RaftTransport.mkRaftMessage(state.serverName, RequestVoteReply.newBuilder() .setFollowerName(state.serverName) .setTerm(voteRequest.getTerm()) .setFollowerTerm(state.currentTerm) .setVoteGranted(voteGranted) .build()); } else { log.trace("{} - {} we're not allowed to perform this action; responding with a rejected vote", state.serverName, methodName); reply = RaftTransport.mkRaftMessage(state.serverName, RequestVoteReply.newBuilder() .setFollowerName(state.serverName) .setTerm(voteRequest.getTerm()) .setFollowerTerm(state.currentTerm) .setVoteGranted(false) .build()); } replyLeader.accept(reply); } /** {@inheritDoc} */ @Override public void receiveRequestVotesReply(RequestVoteReply reply, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "RequestVoteReply"; log.trace("{} - [{}] {} from {}; term={} follower_term={} vote_granted={}", state.serverName, transport.now(), methodName, reply.getFollowerName(), reply.getTerm(), reply.getFollowerTerm(), reply.getVoteGranted()); if (canPerformFollowerAction(methodName, reply.getTerm(), true)) { // 1. Grant the vote if (reply.getVoteGranted()) { state.receiveVoteFrom(reply.getFollowerName()); log.trace("{} - {} received vote; have {} votes total ({})", state.serverName, methodName, state.votesReceived.size(), state.votesReceived); // 2. Check if we won the election if (state.votesReceived.size() > state.log.getQuorumMembers().size() / 2) { // 3. If we won the election, elect ourselves if (state.leadership != RaftState.LeadershipStatus.LEADER) { state.elect(now); log.info("{} - Raft won an election for term {} (time={} members={})", state.serverName, this.state.currentTerm, now, state.log.getQuorumMembers()); broadcastAppendEntries(now, false, true); // immediately broadcast our leadership status } else { log.trace("{} - {} already elected to term {}", state.serverName, methodName, this.state.currentTerm); } } } } } /** {@inheritDoc} */ @Override public void triggerElection(long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "triggerElection"; // The request we're sending. This does not need to be sent in a lock RequestVoteRequest voteRequest; // 1. Become a candidate, if not already one if (!this.state.isCandidate()) { state.becomeCandidate(); } assert this.state.isCandidate() : "Should not be requesting votes if we're not a candidate"; log.info("{} - Raft triggered an election with term {} (time={} chkpt={} cluster={} leader={})", state.serverName, state.currentTerm, now, state.electionTimeoutCheckpoint, state.log.getQuorumMembers(), state.leader.orElse("<unknown>")); // 2. Initiate Election // 2.1. Increment currentTerm state.setCurrentTerm(state.currentTerm + 1); // 2.2. Vote for self state.voteFor(state.serverName); // 2.3. Reset election timer Optional<String> leader = state.leader; state.resetElectionTimeout(now, state.serverName); // propose ourselves as the leader if (!leader.equals(state.leader)) { log.info("{} - {}; registered new leader={} old leader={} time={}", state.serverName, methodName, state.leader.orElse("<none>"), leader.orElse("<none>"), now); } voteRequest = RequestVoteRequest.newBuilder() .setTerm(state.currentTerm) .setCandidateName(state.serverName) .setLastLogIndex(state.log.getLastEntryIndex()) .setLastLogTerm(state.log.getLastEntryTerm()) .build(); // 3. Check if we won the election by default (i.e., we're the only node) if (state.votesReceived.size() > state.log.getQuorumMembers().size() / 2) { if (state.leadership != RaftState.LeadershipStatus.LEADER) { state.elect(now); log.info("{} - Raft won an election (by default) for term {} (time={}; cluster={})", state.serverName, this.state.currentTerm, now, state.log.latestQuorumMembers); } else { log.trace("{} - already elected to term {}", state.serverName, this.state.currentTerm); } } // 4. Send the broadcast // 4.1. (log the broadcast while in a lock) log.trace("{} - Broadcasting requestVote", state.serverName); // 4.2. (send the broadcast) transport.broadcastTransport(this.state.serverName, voteRequest); } // // -------------------------------------------------------------------------- // ADD SERVER // -------------------------------------------------------------------------- // /** {@inheritDoc} */ @Override public CompletableFuture<RaftMessage> receiveAddServerRPC( AddServerRequest addServerRequest, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "AddServerRPC"; log.info("{} - [{}] {}; is_leader={} new_server={}", state.serverName, transport.now(), methodName, state.isLeader(), addServerRequest.getNewServer()); if (state.isLeader()) { // Step 1: Make sure we're the leader // Case: We're on the leader -- add the server clusterMembershipFuture = clusterMembershipFuture.thenApply(x -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); return RaftMessage.newBuilder().setSender(state.serverName).build(); }); // Step 2: Catch up the new server for a fixed number of rounds. state.observeLifeFrom(addServerRequest.getNewServer(), now); // important so that we initialize matchIndex and nextIndex long addServerMatchIndex = state.matchIndex.orElse(new HashMap<>()).getOrDefault(addServerRequest.getNewServer(), 0L); if (addServerMatchIndex < state.log.getLastEntryIndex()) { // if we don't have a log or we already have a full match (this was a shadow node before), we can skip this step for (int roundI = 0; roundI < 3; ++roundI) { final long roundNum = roundI + 1; long timeout = Math.max(5000, Math.min(1000, this.electionTimeoutMillisRange().begin * (3 - roundI) / 2)); long currentMatchIndex = state.matchIndex.orElse(new HashMap<>()).getOrDefault(addServerRequest.getNewServer(), 0L); if (currentMatchIndex == state.log.getLastEntryIndex()) { break; } clusterMembershipFuture = clusterMembershipFuture.thenCompose(message -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); log.trace("{} - {}.2; round={} is_leader={}", state.serverName, methodName, roundNum, state.isLeader()); // Check for errors if (message.getAddServerReply() != AddServerReply.getDefaultInstance()) { return CompletableFuture.completedFuture(message); } if (!state.isLeader()) { return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build()); } // Send the next catch-up request try { log.trace("{} - {}.2 sending_append_entries round={} term={} nextIndex={}", state.serverName, methodName, roundNum, addServerRequest.getNewServer(), message.getAppendEntriesReply().getTerm(), message.getAppendEntriesReply().getNextIndex()); return rpcAppendEntries(addServerRequest.getNewServer(), currentMatchIndex+1, timeout); } catch (Exception t) { t.printStackTrace(); log.warn("{} - {}.2 Could not execute Raft update for server {}; is the server up? Exception: <{}>", state.serverName, methodName, addServerRequest.getNewServer(), t.getClass() + ": " + t.getMessage()); return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.OTHER_ERROR)).build()); } }); } } else { log.trace("{} - {}.2; no update needed, so skipping updating the new server", state.serverName, methodName); } // Step 3: Wait until the previous configuration in log is committed clusterMembershipFuture = clusterMembershipFuture.thenCompose(message -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); log.trace("{} - {}.3; is_leader={}", state.serverName, methodName, state.isLeader()); // 3.1. Propagate errors through if (message.getAddServerReply() != AddServerReply.getDefaultInstance()) { return CompletableFuture.completedFuture(message); } if (!state.isLeader()) { return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build()); } // 3.2. Get last configuration Optional<RaftLogEntryLocation> location = state.log.lastConfigurationEntryLocation(); if (location.isPresent()) { // 3.3A. Case: there was a configuration: wait for it to commit log.trace("{} - {}.3 waiting for commit", state.serverName, methodName); broadcastAppendEntries(transport.now(), false, true); return state.log.createCommitFuture(location.get().index, location.get().term, true).thenApply(success -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); log.trace("{} - {}.3 committed; success={}", state.serverName, methodName, success); if (success) { broadcastAppendEntries(transport.now(), false, true); return RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.OK)).build(); } else { return RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.OTHER_ERROR)).build(); } }); } else { // 3.3B. Case: there was no configuration: it's axiomatically committed return CompletableFuture.completedFuture(message); } }); // Step 4: Append new entry and wait for commit clusterMembershipFuture = clusterMembershipFuture.thenCompose(message -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); RaftLogEntryLocation location; log.trace("{} - {}.4; is_leader={}", state.serverName, methodName, state.isLeader()); // 4.1. Propagate errors through if (message.getAddServerReply().getStatus() != MembershipChangeStatus.OK) { return CompletableFuture.completedFuture(message); } if (!state.isLeader()) { return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build()); } // 4.2. Time out if we've been waiting too long // This is important to prevent the case where something has gone suboptimally in the RPC // (e.g., we didn't have majority for a long time, the server took too long to update, etc.) // and we may not want to blindly add a now-bad server to the configuration. if (transport.now() - now > MACHINE_DOWN_TIMEOUT) { return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.TIMEOUT)).build()); } // 4.3. Submit configuration Set<String> newMembership = new HashSet<>(state.log.getQuorumMembers()); boolean force = !newMembership.add(addServerRequest.getNewServer()); if (!force && !addServerRequest.getQuorumList().isEmpty() && !newMembership.equals(new HashSet<>(addServerRequest.getQuorumList()))) { log.warn("{} - {} consistency error (forcing consistency); adding={} newMembership={} presumedMembership={}", state.serverName, methodName, addServerRequest.getNewServer(), newMembership, addServerRequest.getQuorumList()); newMembership = new HashSet<>(addServerRequest.getQuorumList()); force = true; } location = state.reconfigure(newMembership, force, now); log.info("{} - {} submitted new configuration to log: {}", state.serverName, methodName, newMembership); // This is the point of no return -- the new configuration has been committed to the log // 4.4. Wait for the configuration to commit log.trace("{} - {}.4 waiting for commit", state.serverName, methodName); // 4.4.1. Broadcast a heartbeat to speed things along broadcastAppendEntries(transport.now(), false, true); // 4.4.2. Set up the commit future CompletableFuture<Boolean> commitFuture = state.log.createCommitFuture(location.index, location.term, true); // 4.4.3. Actually wait on the commit return commitFuture.thenApply(success -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); log.trace("{} - {}.4 committed; success={}", state.serverName, methodName, success); if (success) { log.info("{} - {} committed new configuration to log: {}", state.serverName, methodName, state.log.committedQuorumMembers); broadcastAppendEntries(transport.now(), false, true); return RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.OK)).build(); } else { return RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.OTHER_ERROR)).build(); } }); }); // Step 5: Reply CompletableFuture<RaftMessage> rtn = new CompletableFuture<>(); clusterMembershipFuture.handle((result, ex) -> { log.trace("{} - {}.5 complete; result={} have_exception={}", state.serverName, methodName, result == null ? "<exception>" : result.getAddServerReply().getStatus(), ex != null); if (ex != null) { log.warn("Exception on addServer", ex); } lastClusterMembershipChange = transport.now(); if (result != null) { rtn.complete(result); } else { rtn.complete(RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.TIMEOUT)).build()); } return result; }); return rtn; } else { if (state.leader.map(leader -> !leader.equals(this.state.serverName)).orElse(false)) { // Case: We're not the leader -- forward it to the leader if (addServerRequest.getForwardedByList().contains(state.serverName)) { // Case: We're being forwarded this message in a loop (we've forwarded this message in the past), so fail it log.info("{} - {}; we've been forwarded our own message back to us in a loop. Failing the message", state.serverName, methodName); return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply .newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build()); } else { // Case: We're not the leader -- forward it to the leader log.trace("{} - got {}; forwarding request to {}", state.serverName, methodName, this.state.leader.orElse("<unknown>")); return transport.rpcTransportAsFuture(state.serverName, state.leader.orElse("<unknown>"), addServerRequest.toBuilder().addForwardedBy(state.serverName).build(), (result, exception) -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (result != null) { return result; } else { log.warn("{} - {} Failure: <{}>", state.serverName, methodName, exception == null ? "unknown error" : (exception.getClass().getName() + ": " + exception.getMessage())); return RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply.newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build(); } }, this.drivingThreadQueue, this.electionTimeoutMillisRange().end); } } else { // Case: We're not the leader, and we don't know who is. // We have no choice but to fail the request. log.info("{} - got {}; we're not the leader and don't know who the leader is", state.serverName, methodName); return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setAddServerReply(AddServerReply .newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build()); } } } // // -------------------------------------------------------------------------- // REMOVE SERVER // -------------------------------------------------------------------------- // /** {@inheritDoc} */ @Override public CompletableFuture<RaftMessage> receiveRemoveServerRPC( RemoveServerRequest removeServerRequest, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "RemoveServerRPC"; log.info("{} - [{}] {}; is_leader={} to_remove={}", state.serverName, transport.now(), methodName, state.isLeader(), removeServerRequest.getOldServer()); if (state.isLeader()) { // Step 1: Make sure we're the leader // Case: We're on the leader -- remove the server clusterMembershipFuture = clusterMembershipFuture.thenApply(x -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); return RaftMessage.newBuilder().setSender(state.serverName).build(); }); // Step 2: Wait until the previous configuration in log is committed clusterMembershipFuture = clusterMembershipFuture.thenCompose(message -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); log.trace("{} - {}.2; is_leader={}", state.serverName, methodName, state.isLeader()); // 2.1. Propagate errors through if (message.getAddServerReply().getStatus() != MembershipChangeStatus.OK) { return CompletableFuture.completedFuture(message); } if (!state.isLeader()) { return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply.newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build()); } // 2.2. Get last configuration Optional<RaftLogEntryLocation> location = state.log.lastConfigurationEntryLocation(); if (location.isPresent()) { // 2.3A. Case: there was a configuration: wait for it to commit log.trace("{} - {}.2 waiting for commit", state.serverName, methodName); broadcastAppendEntries(transport.now(), false, true); return state.log.createCommitFuture(location.get().index, location.get().term, true).thenApply(success -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); log.trace("{} - {}.2 committed; success={}", state.serverName, methodName, success); if (success) { broadcastAppendEntries(transport.now(), false, true); return RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply.newBuilder() .setStatus(MembershipChangeStatus.OK)).build(); } else { return RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply.newBuilder() .setStatus(MembershipChangeStatus.OTHER_ERROR)).build(); } }); } else { // 2.3B. Case: there was no configuration: it's axiomatically committed return CompletableFuture.completedFuture(message); } }); // Step 3: Append new entry and wait for commit clusterMembershipFuture = clusterMembershipFuture.thenCompose(message -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); RaftLogEntryLocation location; log.trace("{} - {}.3; is_leader={}", state.serverName, methodName, state.isLeader()); // 3.1. Propagate errors through if (message.getAddServerReply().getStatus() != MembershipChangeStatus.OK) { return CompletableFuture.completedFuture(message); } if (!state.isLeader()) { return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply.newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build()); } // 3.2. Time out if we've been waiting too long // This is important to prevent the case where something has gone suboptimally in the RPC // (e.g., we didn't have majority for a long time, the server took too long to update, etc.) // and we may not want to blindly add a now-bad server to the configuration. if (transport.now() - now > MACHINE_DOWN_TIMEOUT) { return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply.newBuilder() .setStatus(MembershipChangeStatus.TIMEOUT)).build()); } // 3.3. Submit configuration Set<String> newMembership = new HashSet<>(state.log.getQuorumMembers()); boolean force = !newMembership.remove(removeServerRequest.getOldServer()); if (!force && !removeServerRequest.getQuorumList().isEmpty() && !newMembership.equals(new HashSet<>(removeServerRequest.getQuorumList()))) { log.warn("{} - {} consistency error (forcing consistency); adding={} newMembership={} presumedMembership={}", state.serverName, methodName, removeServerRequest.getOldServer(), newMembership, removeServerRequest.getQuorumList()); newMembership = new HashSet<>(removeServerRequest.getQuorumList()); force = true; } location = state.reconfigure(newMembership, force, now); log.info("{} - {} submitted new configuration to log: {}", state.serverName, methodName, newMembership); // This is the point of no return -- the membership has been submitted // 3.4. Wait for the configuration to commit log.trace("{} - {}.3 waiting for commit", state.serverName, methodName); // 3.4.1. Broadcast a heartbeat to speed things along broadcastAppendEntries(transport.now(), false, true); // 4.4.2. Set up the commit future CompletableFuture<Boolean> commitFuture = state.log.createCommitFuture(location.index, location.term, true); // 4.4.3. Actually wait on the commit future return commitFuture.thenApply(success -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); log.trace("{} - {}.3 committed; success={}", state.serverName, methodName, success); if (success) { log.info("{} - {} committed new configuration to log: {}", state.serverName, methodName, state.log.committedQuorumMembers); // (clear the removed node's lastMessageTimestamp) state.lastMessageTimestamp.ifPresent(map -> map.remove(removeServerRequest.getOldServer())); // (broadcast the commit) broadcastAppendEntries(transport.now(), true, true); // corner case: force the append to be broadcast // (return) return RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply.newBuilder() .setStatus(MembershipChangeStatus.OK)).build(); } else { return RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply.newBuilder() .setStatus(MembershipChangeStatus.OTHER_ERROR)).build(); } }); }); // Step 4: Reply CompletableFuture<RaftMessage> rtn = new CompletableFuture<>(); clusterMembershipFuture.handle((result, ex) -> { log.trace("{} - {}.5 complete; result={} have_exception={}", state.serverName, methodName, result == null ? "<exception>" : result.getAddServerReply().getStatus(), ex != null); if (ex != null) { log.warn("Exception on removeServer", ex); } lastClusterMembershipChange = transport.now(); if (result != null) { // If we've removed ourselves, step down from leadership. if (removeServerRequest.getOldServer().equals(state.serverName) && result.getRemoveServerReply().getStatus() == MembershipChangeStatus.OK) { state.stepDownFromElection(); } // Then, return rtn.complete(result); } else { rtn.complete(RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply.newBuilder() .setStatus(MembershipChangeStatus.TIMEOUT)).build()); } return result; }); return rtn; } else { if (state.leader.map(leader -> !leader.equals(this.state.serverName)).orElse(false)) { // Case: We're not the leader -- forward it to the leader if (removeServerRequest.getForwardedByList().contains(state.serverName)) { // Case: We're being forwarded this message in a loop (we've forwarded this message in the past), so fail it log.info("{} - {}; we've been forwarded our own message back to us in a loop. Failing the message", state.serverName, methodName); return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply .newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build()); } else { log.trace("{} - got {}; forwarding request to {}", state.serverName, methodName, this.state.leader.orElse("<unknown>")); return transport.rpcTransportAsFuture(state.serverName, state.leader.orElse("<unknown>"), removeServerRequest.toBuilder().addForwardedBy(state.serverName).build(), (result, exception) -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (result != null) { return result; } else { log.warn("{} - {} Failure: <{}>", state.serverName, methodName, exception == null ? "unknown error" : (exception.getClass().getName() + ": " + exception.getMessage())); return RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply.newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build(); } }, this.drivingThreadQueue, this.electionTimeoutMillisRange().end + 100); } } else { // Case: We're not the leader, and we don't know who is. // We have no choice but to fail the request. log.info("{} - got {}; we're not the leader and don't know who the leader is", state.serverName, methodName); return CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setRemoveServerReply(RemoveServerReply .newBuilder() .setStatus(MembershipChangeStatus.NOT_LEADER)).build()); } } } // // -------------------------------------------------------------------------- // CONTROL // -------------------------------------------------------------------------- // /** {@inheritDoc} */ @Override public CompletableFuture<RaftMessage> receiveApplyTransitionRPC(ApplyTransitionRequest transition, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); String methodName = "ReceiveApplyTransition"; log.trace("{} - [{}] {}; is_leader={}", state.serverName, transport.now(), methodName, this.state.isLeader()); CompletableFuture<RaftMessage> rtn; if (state.isLeader()) { // Case: We're on the leader -- apply the transition RaftLogEntryLocation location = state.transition( transition.getTransition().isEmpty() ? Optional.empty() : Optional.of(transition.getTransition().toByteArray()), "".equals(transition.getNewHospiceMember()) ? Optional.empty() : Optional.of(transition.getNewHospiceMember()) ); rtn = state.log.createCommitFuture(location.index, location.term, true).handle((success, exception) -> { // The transition was either committed or overwritten assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); ApplyTransitionReply.Builder reply = ApplyTransitionReply .newBuilder() .setTerm(state.currentTerm) .setNewEntryIndex(-1) // just so it's not picked up as the default proto. overwritten below .setSuccess(success != null ? success : false); if (success != null && success) { reply .setNewEntryIndex(location.index) .setNewEntryTerm(location.term); } else { log.info("{} - {}; failed transition (on leader; could not commit) @ time={}", state.serverName, methodName, now, exception); } // Reply return RaftMessage.newBuilder().setSender(state.serverName).setApplyTransitionReply(reply).build(); }); // Early broadcast message broadcastAppendEntries(now, this.state.log.latestQuorumMembers.size() <= 1, false); // Update our leader invariants this.updateLeaderInvariantsPostMessage(Optional.empty(), now); } else if (state.leader.map(leader -> !leader.equals(this.state.serverName)).orElse(false)) { if (transition.getForwardedByList().contains(state.serverName)) { // Case: We're being forwarded this message in a loop (we've forwarded this message in the past), so fail it log.info("{} - {}; we've been forwarded our own message back to us in a loop. Failing the message", state.serverName, methodName); rtn = CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setApplyTransitionReply(ApplyTransitionReply .newBuilder() .setTerm(state.currentTerm) .setNewEntryIndex(-2) .setSuccess(false)).build()); } else { // Case: We're not the leader -- forward it to the leader assert !state.leader.map(x -> x.equals(this.serverName())).orElse(false) : "We are sending a message to the leader, but we think we're the leader!"; log.trace("{} - [{}] {}; forwarding request to {}", state.serverName, transport.now(), methodName, this.state.leader.orElse("<unknown>")); // Forward the request rtn = transport.rpcTransportAsFuture( state.serverName, state.leader.orElse("<unknown>"), transition.toBuilder().addForwardedBy(state.serverName).build(), (result, exception) -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (result != null) { log.trace("{} - {}; received reply to forwarded message", state.serverName, methodName); return result; } else { log.warn("{} - [{}] {} Failure: <{}>; is_leader={} leader={}", state.serverName, transport.now(), methodName, exception == null ? "unknown error" : (exception.getClass().getName() + ": " + exception.getMessage()), state.isLeader(), state.leader.orElse("<unknown>")); return RaftMessage.newBuilder().setSender(state.serverName).setApplyTransitionReply(ApplyTransitionReply .newBuilder() .setTerm(state.currentTerm) .setNewEntryIndex(-3) .setSuccess(false)).build(); } }, this.drivingThreadQueue, this.electionTimeoutMillisRange().end) .thenCompose(leaderResponse -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); // Then wait for it to commit locally if (leaderResponse.getApplyTransitionReply().getSuccess()) { log.trace("{} - {}; waiting for commit", state.serverName, methodName); long index = leaderResponse.getApplyTransitionReply().getNewEntryIndex(); long term = leaderResponse.getApplyTransitionReply().getNewEntryTerm(); return state.log.createCommitFuture(index, term, true).thenApply(success -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); log.trace("{} - {}; Entry @ {} (term={}) is committed in the local log", state.serverName, methodName, index, term); // The transition was either committed or overwritten ApplyTransitionReply.Builder reply = ApplyTransitionReply .newBuilder() .setTerm(state.currentTerm) .setNewEntryIndex(-4) // just so this isn't the default proto. Overwritten below .setSuccess(success); if (success) { reply .setNewEntryIndex(index) .setNewEntryTerm(term); } else { log.info("{} - {}; failed transition (on follower) @ time={}", state.serverName, methodName, transport.now()); } return RaftMessage.newBuilder().setSender(state.serverName).setApplyTransitionReply(reply).build(); }); } else { log.info("{} - {}; failed to apply transition (reply proto had failure marked); returning failure", state.serverName, methodName); return CompletableFuture.completedFuture(leaderResponse); } }); } } else { // Case: We're not the leader, and we don't know who is. // We have no choice but to fail the request. log.info("{} - {}; we're not the leader and don't know who the leader is", state.serverName, methodName); rtn = CompletableFuture.completedFuture(RaftMessage.newBuilder().setSender(state.serverName).setApplyTransitionReply(ApplyTransitionReply .newBuilder() .setTerm(state.currentTerm) .setNewEntryIndex(-5) .setSuccess(false)).build()); } // Return return rtn; } /** {@inheritDoc} */ @Override public void heartbeat(long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); long begin = transport.now(); Object timerPrometheusBegin = Prometheus.startTimer(summaryTiming, "heartbeat"); long sectionBegin; try { if (this.state.isLeader()) { assert checkDuration("leadership check", begin, transport.now()); // Case: do a leader heartbeat sectionBegin = transport.now(); log.trace("{} - heartbeat (leader) @ time={} cluster={}", state.serverName, now, state.log.getQuorumMembers()); assert checkDuration("get quorum members", begin, transport.now()); broadcastAppendEntries(now, false, true); // the heartbeat. if (Thread.interrupted()) { throw new RuntimeInterruptedException(); } assert checkDuration("broadcast", sectionBegin, transport.now()); // Check if we should scale the cluster if (state.targetClusterSize >= 0) { // only do this if we don't have a fixed cluster sectionBegin = transport.now(); if (clusterMembershipFuture.getNow(null) != null) { // if we're not still waiting on membership changes Optional<String> maybeServer; if ((maybeServer = state.serverToRemove(now, MACHINE_DOWN_TIMEOUT)).isPresent()) { // Case: we want to scale down the cluster log.info("{} - Detected Raft cluster is too large ({} > {}) or we have a delinquent server; scaling down by removing {} (latency {}) current_time={}", state.serverName, state.log.getQuorumMembers().size(), state.targetClusterSize, maybeServer.get(), transport.now() - maybeServer.flatMap(server -> state.lastMessageTimestamp.map(x -> x.get(server))).orElse(-1L), now); this.receiveRPC(RaftTransport.mkRaftRPC(state.serverName, EloquentRaftProto.RemoveServerRequest.newBuilder() .setOldServer(maybeServer.get()) .build()), now ); assert checkDuration("remove server", sectionBegin, transport.now()); } else if ((maybeServer = state.serverToAdd(now, electionTimeoutMillisRange().begin)).isPresent()) { // note: add timeout is different from remove timeout. Much more strict to add than to remove // Case: we want to scale up the cluster log.info("{} - Detected Raft cluster is too small ({} < {}); scaling up by adding {} (latency {}) current_time={}", state.serverName, state.log.getQuorumMembers().size(), state.targetClusterSize, maybeServer.get(), transport.now() - maybeServer.flatMap(server -> state.lastMessageTimestamp.map(x -> x.get(server))).orElse(-1L), now); this.receiveRPC(RaftTransport.mkRaftRPC(state.serverName, EloquentRaftProto.AddServerRequest.newBuilder() .setNewServer(maybeServer.get()) .build()), now ); assert checkDuration("add server", sectionBegin, transport.now()); } } if (Thread.interrupted()) { throw new RuntimeInterruptedException(); } assert checkDuration("size checks", sectionBegin, transport.now()); } // Check if anyone has gone offline sectionBegin = transport.now(); if (state.log.stateMachine instanceof KeyValueStateMachine) { Set<String> toKillSet = state.killNodes(now, MACHINE_DOWN_TIMEOUT); CompletableFuture<RaftMessage> future = CompletableFuture.completedFuture(null); for (String deadNode : toKillSet) { future = future.thenCompose(lastSuccess -> { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); log.info("{} - Clearing transient data for node {}", state.serverName, deadNode); return receiveApplyTransitionRPC(ApplyTransitionRequest.newBuilder() .setTransition(ByteString.copyFrom(KeyValueStateMachine.createClearTransition(deadNode))) .build(), now) .handle((response, exception) -> { if (exception != null || response == null || !response.getApplyTransitionReply().getSuccess()) { state.revive(deadNode); } return null; }); }); } } assert checkDuration("offline check", sectionBegin, transport.now()); } else { // Case: do a follower heartbeat log.trace("{} - heartbeat (follower) @ time={} cluster={}", state.serverName, now, state.log.getQuorumMembers()); if (state.shouldTriggerElection(now, electionTimeoutMillisRange())) { this.triggerElection(now); } } } finally { Prometheus.observeDuration(timerPrometheusBegin); assert checkDuration("total", begin, transport.now()); } } /** * A helper method for checking if an operation took too long. * * @param description The description of the task that timed out. * @param begin The begin time of the operation * @param now The current time. * * @return True if the operation took too long */ @SuppressWarnings("Duplicates") private boolean checkDuration(String description, long begin, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); long timeElapsed = now - begin; if (timeElapsed > 50) { long lastGcTime = -1L; try { for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) { com.sun.management.GarbageCollectorMXBean sunGcBean = (com.sun.management.GarbageCollectorMXBean) gcBean; GcInfo lastGcInfo = sunGcBean.getLastGcInfo(); if (lastGcInfo != null) { lastGcTime = lastGcInfo.getStartTime(); } } } catch (Throwable t) { log.warn("Could not get GC info -- are you running on a non-Sun JVM?"); } boolean interruptedByGC = false; if (lastGcTime > begin && lastGcTime < now) { interruptedByGC = true; } OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class); log.warn("{} - Raft took >50ms ({}) on step '{}'; leadership={} system_load={} interrupted_by_gc={}", state.serverName, TimerUtils.formatTimeDifference(timeElapsed), description, state.leadership, osBean.getSystemLoadAverage(), interruptedByGC); } return true; // always return true, or else we throw an assert } /** {@inheritDoc} */ @Override public boolean bootstrap(boolean force) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (force || (this.state.targetClusterSize >= 0 && this.state.log.getQuorumMembers().isEmpty())) { // only if we need bootstrapping state.bootstrap(force); return true; } else { return false; } } /** {@inheritDoc} */ @Override public void stop(boolean kill) { } /** {@inheritDoc} */ @Override public boolean isRunning() { return true; } /** {@inheritDoc} */ @Override public void receiveBadRequest(RaftMessage message) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (message.getApplyTransitionReply() != ApplyTransitionReply.getDefaultInstance()) { log.warn("{} - Got an apply transition reply -- likely the dangling reply of a timeout somewhere", state.serverName); } else { log.warn("{} - Bad Raft message {}", state.serverName, message.toString()); } } @Override public Optional<RaftLifecycle> lifecycle() { // Don't check for driving thread -- this is final anyways return lifecycle; } @Override public RaftTransport getTransport() { return transport; } /** * Print any errors we can find in the Raft node. */ public List<String> errors() { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); List<String> errors = new ArrayList<>(); if (clusterMembershipFuture.getNow(null) == null) { errors.add("Membership change in progress (future is not empty). My state: " + state.leadership + "; leader=" + state.leader.orElse("<unknown>")); } if (state.lastMessageTimestamp.map(Map::size).orElse(0) > 1000) { errors.add("Keeping track of >1000 heartbeat (" + state.lastMessageTimestamp.map(Map::size).orElse(0) + ")"); } if (state.electionTimeoutCheckpoint < 0) { errors.add("No election timeout present (perhaps means heartbeats are not propagating?): " + Instant.ofEpochMilli(state.electionTimeoutCheckpoint)); } long timeSinceBroadcast = transport.now() - (Arrays.stream(lastBroadcastTimes).max().orElse(0)); if (state.isLeader() && timeSinceBroadcast > this.heartbeatMillis() * 10) { errors.add("Last broadcast was " + TimerUtils.formatTimeDifference(timeSinceBroadcast) + " ago"); } return errors; } // // -------------------------------------------------------------------------- // INVARIANTS // -------------------------------------------------------------------------- // /** * This is called on every RPC communication step to ensure that we can perform a follower * action. * * @param rpcName The name of the RPC, for debugging. * @param remoteTermNumber The term number from the server. * @param isRpcReply True if we're inside an RPC reply * * @return true if we observed a compatible term number */ private boolean canPerformFollowerAction(String rpcName, long remoteTermNumber, boolean isRpcReply) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (remoteTermNumber < state.currentTerm && !isRpcReply) { // Someone is broadcasting with an older term -- ignore the message log.trace("{} - {} cannot perform action: remoteTerm={} < currentTerm={}", state.serverName, rpcName, remoteTermNumber, state.currentTerm); return false; } else if (remoteTermNumber > state.currentTerm) { // Someone is broadcasting with a newer term -- defer to them log.trace("{} - {} detected remoteTerm={} > currentTerm={} -- forced into follower state but otherwise continuing", state.serverName, rpcName, remoteTermNumber, state.currentTerm); state.stepDownFromElection(); state.setCurrentTerm(remoteTermNumber); assert state.leadership == RaftState.LeadershipStatus.OTHER; return true; } else { // Terms match -- everything is OK return true; } } /** * A short helper wrapping {@link #canPerformLeaderAction(String, long)} and * {@link #updateLeaderInvariantsPostMessage(Optional, long)}. */ private void asLeader(String followerName, long remoteTerm, long now, Runnable fn) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (canPerformLeaderAction(followerName, remoteTerm)) { try { assert state.isLeader() : "We should be a leader if we get this far performing a leader action"; fn.run(); } finally { updateLeaderInvariantsPostMessage(Optional.of(followerName), now); } } else { log.trace("{} - Leader prereqs failed.", this.state.serverName); } } /** * Runs before a message is processed to make sure that we can perform a leader action. * * <p> * Consider calling {@link #asLeader(String, long, long, Runnable)} rather than calling this * function directly. * </p> * * @param followerName The follower we received the message from. * @param remoteTerm The term received from the follower * * @return True if the leader can continue with the request. Otherwise, we should * handle the error somehow. */ private boolean canPerformLeaderAction(String followerName, long remoteTerm) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (!state.isLeader()) { log.trace("{} - presumed leader is not a leader", state.serverName); return false; } if (followerName.isEmpty()) { log.warn("{} - Got a message with no follower name. This is an error!", state.serverName); return false; } if (remoteTerm < state.currentTerm) { // Someone is broadcasting with an older term -- ignore the message, but throw a warning because this is weird and // should be very rare log.warn("{} - leader cannot perform action. remoteTerm={} < currentTerm={}", state.serverName, remoteTerm, state.currentTerm); return false; } else if (remoteTerm > state.currentTerm) { // Someone is broadcasting with a newer term -- defer to them log.trace("{} - detected remoteTerm={} > currentTerm={} -- forced into follower state", state.serverName, remoteTerm, state.currentTerm); state.stepDownFromElection(); state.setCurrentTerm(remoteTerm); assert state.leadership == RaftState.LeadershipStatus.OTHER; return false; } else { // Terms match -- everything is OK return true; } } /** * Run all of the invariants that should be true on the leader. This should be called after * every successful message is received by the leader. * * <p> * Consider calling {@link #asLeader(String, long, long, Runnable)} rather than calling this * function directly. * </p> * * @param followerName The follower we received the message from. * @param now The current time -- this is useful if we want to mock time. */ private void updateLeaderInvariantsPostMessage(Optional<String> followerName, long now) { assert drivingThreadId < 0 || drivingThreadId == Thread.currentThread().getId() : "Eloquent Raft Algorithm should only be run from the driving thread (" + drivingThreadId + ") but is being driven by " + Thread.currentThread(); if (state.isLeader()) { // 1. Observe that a follower is still alive followerName.ifPresent(s -> this.state.observeLifeFrom(s, now)); // 2. If there exists an N such that N > commitIndex, a majority of matchIndex[i] >= N, // and log[N].term == currentTerm, then set commitIndex = N. this.state.matchIndex.ifPresent(matchIndex -> { Set<String> clusterMembers = this.state.log.getQuorumMembers(); if (!clusterMembers.isEmpty()) { // 2.1. Get the set of relevant match indices long[] matchIndices = clusterMembers.stream().mapToLong(member -> { if (this.state.serverName.equals(member)) { return this.state.log.getLastEntryIndex(); } else { assert matchIndex.containsKey(member) : "no match index for member " + member; return matchIndex.get(member); } }).toArray(); // 2.2. Find the median index Arrays.sort(matchIndices); long medianIndex; if (matchIndices.length % 2 == 0) { medianIndex = matchIndices[matchIndices.length / 2 - 1]; // round pessimistically (len 4 -> index 1) -- we need a majority, not just a tie } else { medianIndex = matchIndices[matchIndices.length / 2]; // no need to round (len 3 -> index 1) } // log.trace("{} - matchIndices={} medianIndex={} commitIndex={}", state.serverName, matchIndices, medianIndex, state.commitIndex()); // 2.3. Commit up to the median index if (medianIndex > state.commitIndex() && state.log.getLastEntryTerm() == state.currentTerm) { log.trace("{} - Committing up to index {}; matchIndex={} -> {}", state.serverName, medianIndex, matchIndex, matchIndices); state.commitUpTo(medianIndex, now); // 2.4. Broadcast the commit immediately if (followerName.isPresent()) { // but only if this is from a particular follower's update broadcastAppendEntries(now, false, false); } } } }); } } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EloquentRaftAlgorithm that = (EloquentRaftAlgorithm) o; return Objects.equals(state, that.state); } /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(state); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/EloquentRaftNode.java
package ai.eloquent.raft; import ai.eloquent.error.RaftErrorListener; import ai.eloquent.util.*; import com.google.protobuf.ByteString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.time.Duration; import java.util.*; import java.util.concurrent.*; /** * A node in the Raft cluster. * This is as lightweight a class as possible, marrying * a {@link RaftAlgorithm} (purely functional with no actual transport logic) * with an {@link RaftTransport} (pure transport logic) * to produce a functioning node in the cluster. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class EloquentRaftNode implements AutoCloseable { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(EloquentRaftNode.class); /** Keeps track of existing {@link RaftErrorListener} **/ private static ArrayList<RaftErrorListener> errorListeners = new ArrayList<>(); /** * Keeps track of an additional {@link RaftErrorListener} in this class * @param errorListener */ protected void addErrorListener(RaftErrorListener errorListener) { errorListeners.add(errorListener); } /** * Stop listening from a specific {@link RaftErrorListener} * @param errorListener The error listener to be removed */ protected void removeErrorListener(RaftErrorListener errorListener) { errorListeners.remove(errorListener); } /** * Clears all the {@link RaftErrorListener}s attached to this class. */ protected void clearErrorListeners() { errorListeners.clear(); } /** * Alert each of the {@link RaftErrorListener}s attached to this class. */ private void throwRaftError(String incidentKey, String debugMessage) { errorListeners.forEach(listener -> listener.accept(incidentKey, debugMessage, Thread.currentThread().getStackTrace())); } /** * The Raft algorithm. */ public final RaftAlgorithm algorithm; /** * The Raft transport logic. */ public final RaftTransport transport; /** * The RaftLifecycle object that this Raft node is tied to. */ public final RaftLifecycle lifecycle; /** * If true, this node is still active. * This is used in the timer, and can be shut off via {@link #close()}. */ private boolean alive = true; // Start alive, of course /** * The last time we issued a heartbeat to the algorithm. This is mostly for debugging. */ private long lastHeartbeat; /** * These are hooks we can register on this RaftNode to run right before we begin the official shutdown process. * Created for Theseus to be able to close itself when EloquentRaftNode is shut down by RaftLifecycle. */ private List<Runnable> shutdownHooks = new ArrayList<>(); /** * This is the set of failsafes that are registered to run every so often to ensure that Raft is in an OK state. */ private final List<RaftFailsafe> failsafes = new ArrayList<>(); /** * This is a reference to the heartbeat timer task we have running, so we can clean it up on shutdown. */ private Pointer<SafeTimerTask> heartbeatTimerTask = new Pointer<>(); /** * This is a reference to the failsafe timer task we have running, so we can clean it up on shutdown. */ private Pointer<SafeTimerTask> failsafeTimerTask = new Pointer<>(); /** The straightforward constructor. */ public EloquentRaftNode(RaftAlgorithm algorithm, RaftTransport transport, RaftLifecycle lifecycle) { this.algorithm = algorithm; this.transport = transport; this.lifecycle = lifecycle; this.lastHeartbeat = transport.now(); // Bind to the transport just in case. This should already be bound though try { transport.bind(algorithm); } catch (IOException e) { throw new RuntimeIOException(e); } lifecycle.registerRaft(this); } /** * This adds a hook to run before we shutdown this RaftNode. The hook will run on the thread that calls close() on * this EloquentRaftNode (generally the shutdown hook in RaftLifecycle, from RaftLifecycle.shutdown()). * * @param shutdownHook The hook to run on shutdown */ public void registerShutdownHook(Runnable shutdownHook) { this.shutdownHooks.add(shutdownHook); } /** * This begins the process of discovering and joining the Raft cluster as a member. */ public void start() { // 1. Heartbeat timer SafeTimerTask heartbeatTask = new SafeTimerTask() { /** A thread pool for running Raft heartbeats */ private final ExecutorService pool = lifecycle.managedThreadPool( "raft-heartbeat-" + algorithm.serverName().replace('.', '_'), Math.max(Thread.MAX_PRIORITY - 1, Thread.MIN_PRIORITY) // Raft heartbeats are high priority ); /** {@inheritDoc} */ @Override protected ExecutorService pool() { return pool; // note[gabor] must return a cached pool, or else we recreate the pool on every task } /** {@inheritDoc} */ @Override public void runUnsafe() { try { // Run the heartbeat if (alive) { lastHeartbeat = transport.now(); algorithm.heartbeat(transport.now()); } else { log.info("{} - Stopping heartbeat timer by user request", algorithm.serverName()); this.cancel(); } } catch (Throwable t) { log.warn("Got exception on Raft heartbeat timer task: ", t); StringWriter trace = new StringWriter(); PrintWriter writer = new PrintWriter(trace); t.printStackTrace(writer); throwRaftError("heartbeat_error@" + SystemUtils.HOST, "Exception on Raft heartbeat"); } } }; transport.scheduleAtFixedRate(heartbeatTask, algorithm.heartbeatMillis()); heartbeatTimerTask.set(heartbeatTask); // 2. Failsafe timer SafeTimerTask failsafeTask = new SafeTimerTask() { /** A thread pool for running Raft heartbeats */ private final ExecutorService pool = lifecycle.managedThreadPool( "raft-failsafe-" + algorithm.serverName().replace('.', '_'), Math.max(Thread.MAX_PRIORITY - 1, Thread.MIN_PRIORITY) // Raft heartbeats are high priority ); /** {@inheritDoc} */ @Override protected ExecutorService pool() { return pool; // note[gabor] must return a cached pool, or else we recreate the pool on every task } /** {@inheritDoc} */ @Override public void runUnsafe() { try { // Run the failsafe if (alive) { // Run our any registered failsafes for (RaftFailsafe failsafe : EloquentRaftNode.this.failsafes) { failsafe.heartbeat(EloquentRaftNode.this.algorithm, System.currentTimeMillis()); } lastHeartbeat = transport.now(); } else { log.info("{} - Stopping failsafe timer by user request", algorithm.serverName()); this.cancel(); } } catch (Throwable t) { log.warn("Got exception on Raft failsafe timer task: ", t); } } }; transport.scheduleAtFixedRate(failsafeTask, Duration.ofSeconds(1).toMillis()); failsafeTimerTask.set(failsafeTask); } /** * Bootstrap this node of the cluster. * This will put it into a state where it can become a candidate and start elections. * * @return True if we could bootstrap the node. */ public boolean bootstrap(boolean force) { return algorithm.bootstrap(force); } /** * Submit a transition to Raft. * * @param transition The transition we are submitting. * * @return A future for the transition, marking whether it completed successfully. */ public CompletableFuture<Boolean> submitTransition(byte[] transition) { return algorithm.receiveRPC(RaftTransport.mkRaftRPC(algorithm.serverName(), EloquentRaftProto.ApplyTransitionRequest.newBuilder() .setTransition(ByteString.copyFrom(transition)) .setTerm(algorithm.term()) .build()), transport.now() ).thenApply(reply -> reply.getApplyTransitionReply().getSuccess()); } /** * Return any errors Raft has encountered. */ public List<String> errors() { List<String> errors = new ArrayList<>(); if (algorithm instanceof EloquentRaftAlgorithm) { errors.addAll(((EloquentRaftAlgorithm) algorithm).errors()); } else if (algorithm instanceof SingleThreadedRaftAlgorithm) { errors.addAll(((SingleThreadedRaftAlgorithm) algorithm).errors()); } if (!alive) { errors.add("Node is not alive"); } if (alive) { if (Math.abs(transport.now() - lastHeartbeat) > algorithm.heartbeatMillis() * 2) { errors.add("Last heartbeat was " + TimerUtils.formatTimeSince(lastHeartbeat) + " ago"); } } return errors; } /** * Returns true if we're currently alive, false if we've closed. */ public boolean isAlive() { return this.alive; } /** * This does an orderly shutdown of this member of the Raft cluster, stopping its heartbeats and removing it * from the cluster. * * If blocking is true, this will wait until the * cluster has at least one other member to carry on the state before shutting down. * * <p> * <b>WARNING:</b> once closed, this cannot be reopened * </p> * * @param allowClusterDeath If true, allow the cluster to lose state and completely shut down. * Otherwise, we wait for another live node to show up before shutting * down (the default). */ public void close(boolean allowClusterDeath) { if (this.alive) { log.info(algorithm.serverName() + " - " + "Stopping Raft node {}", this.algorithm.serverName()); for (Runnable runnable : shutdownHooks) { runnable.run(); } RaftAlgorithm.shutdown(this.algorithm, this.transport, allowClusterDeath); this.alive = false; log.info(algorithm.serverName() + " - " + "Stopped Raft node {}", this.algorithm.serverName()); } else { log.warn("Detected double shutdown of {} -- ignoring", this.algorithm.serverName()); } } /** @see #close(boolean) */ @Override public void close() { close(false); } /** * Register a new failsafe to run occasionally on this node. * * @param failsafe the one to register */ public void registerFailsafe(RaftFailsafe failsafe) { this.failsafes.add(failsafe); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/EloquentRaftProto.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: EloquentRaft.proto package ai.eloquent.raft; public final class EloquentRaftProto { private EloquentRaftProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } /** * Protobuf enum {@code ai.eloquent.raft.LogEntryType} */ public enum LogEntryType implements com.google.protobuf.ProtocolMessageEnum { /** * <code>TRANSITION = 0;</code> */ TRANSITION(0), /** * <code>CONFIGURATION = 1;</code> */ CONFIGURATION(1), UNRECOGNIZED(-1), ; /** * <code>TRANSITION = 0;</code> */ public static final int TRANSITION_VALUE = 0; /** * <code>CONFIGURATION = 1;</code> */ public static final int CONFIGURATION_VALUE = 1; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static LogEntryType valueOf(int value) { return forNumber(value); } public static LogEntryType forNumber(int value) { switch (value) { case 0: return TRANSITION; case 1: return CONFIGURATION; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<LogEntryType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< LogEntryType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<LogEntryType>() { public LogEntryType findValueByNumber(int number) { return LogEntryType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.getDescriptor().getEnumTypes().get(0); } private static final LogEntryType[] VALUES = values(); public static LogEntryType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private LogEntryType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:ai.eloquent.raft.LogEntryType) } /** * Protobuf enum {@code ai.eloquent.raft.MembershipChangeStatus} */ public enum MembershipChangeStatus implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> ** The membership change was successful * </pre> * * <code>OK = 0;</code> */ OK(0), /** * <pre> ** A timeout was reached before membership could complete. * </pre> * * <code>TIMEOUT = 1;</code> */ TIMEOUT(1), /** * <pre> ** The node is not the leader. * </pre> * * <code>NOT_LEADER = 2;</code> */ NOT_LEADER(2), /** * <pre> ** Some other error went wrong. This should never happen in normal operation. * </pre> * * <code>OTHER_ERROR = 3;</code> */ OTHER_ERROR(3), UNRECOGNIZED(-1), ; /** * <pre> ** The membership change was successful * </pre> * * <code>OK = 0;</code> */ public static final int OK_VALUE = 0; /** * <pre> ** A timeout was reached before membership could complete. * </pre> * * <code>TIMEOUT = 1;</code> */ public static final int TIMEOUT_VALUE = 1; /** * <pre> ** The node is not the leader. * </pre> * * <code>NOT_LEADER = 2;</code> */ public static final int NOT_LEADER_VALUE = 2; /** * <pre> ** Some other error went wrong. This should never happen in normal operation. * </pre> * * <code>OTHER_ERROR = 3;</code> */ public static final int OTHER_ERROR_VALUE = 3; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static MembershipChangeStatus valueOf(int value) { return forNumber(value); } public static MembershipChangeStatus forNumber(int value) { switch (value) { case 0: return OK; case 1: return TIMEOUT; case 2: return NOT_LEADER; case 3: return OTHER_ERROR; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<MembershipChangeStatus> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< MembershipChangeStatus> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<MembershipChangeStatus>() { public MembershipChangeStatus findValueByNumber(int number) { return MembershipChangeStatus.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.getDescriptor().getEnumTypes().get(1); } private static final MembershipChangeStatus[] VALUES = values(); public static MembershipChangeStatus valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private MembershipChangeStatus(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:ai.eloquent.raft.MembershipChangeStatus) } public interface RaftMessageOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.RaftMessage) com.google.protobuf.MessageOrBuilder { /** * <pre> ** If true, we are expecting a response to this request over the RPC channel. * </pre> * * <code>bool isRPC = 1;</code> */ boolean getIsRPC(); /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ boolean hasAppendEntries(); /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest getAppendEntries(); /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequestOrBuilder getAppendEntriesOrBuilder(); /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ boolean hasRequestVotes(); /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest getRequestVotes(); /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ ai.eloquent.raft.EloquentRaftProto.RequestVoteRequestOrBuilder getRequestVotesOrBuilder(); /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ boolean hasApplyTransition(); /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest getApplyTransition(); /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequestOrBuilder getApplyTransitionOrBuilder(); /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ boolean hasAddServer(); /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ ai.eloquent.raft.EloquentRaftProto.AddServerRequest getAddServer(); /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ ai.eloquent.raft.EloquentRaftProto.AddServerRequestOrBuilder getAddServerOrBuilder(); /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ boolean hasRemoveServer(); /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest getRemoveServer(); /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ ai.eloquent.raft.EloquentRaftProto.RemoveServerRequestOrBuilder getRemoveServerOrBuilder(); /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ boolean hasInstallSnapshot(); /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest getInstallSnapshot(); /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequestOrBuilder getInstallSnapshotOrBuilder(); /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ boolean hasAppendEntriesReply(); /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply getAppendEntriesReply(); /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ ai.eloquent.raft.EloquentRaftProto.AppendEntriesReplyOrBuilder getAppendEntriesReplyOrBuilder(); /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ boolean hasRequestVotesReply(); /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ ai.eloquent.raft.EloquentRaftProto.RequestVoteReply getRequestVotesReply(); /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ ai.eloquent.raft.EloquentRaftProto.RequestVoteReplyOrBuilder getRequestVotesReplyOrBuilder(); /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ boolean hasApplyTransitionReply(); /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply getApplyTransitionReply(); /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReplyOrBuilder getApplyTransitionReplyOrBuilder(); /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ boolean hasAddServerReply(); /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ ai.eloquent.raft.EloquentRaftProto.AddServerReply getAddServerReply(); /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ ai.eloquent.raft.EloquentRaftProto.AddServerReplyOrBuilder getAddServerReplyOrBuilder(); /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ boolean hasRemoveServerReply(); /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ ai.eloquent.raft.EloquentRaftProto.RemoveServerReply getRemoveServerReply(); /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ ai.eloquent.raft.EloquentRaftProto.RemoveServerReplyOrBuilder getRemoveServerReplyOrBuilder(); /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ boolean hasInstallSnapshotReply(); /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply getInstallSnapshotReply(); /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReplyOrBuilder getInstallSnapshotReplyOrBuilder(); /** * <pre> ** The name of the node that sent this message. * </pre> * * <code>string sender = 14;</code> */ java.lang.String getSender(); /** * <pre> ** The name of the node that sent this message. * </pre> * * <code>string sender = 14;</code> */ com.google.protobuf.ByteString getSenderBytes(); public ai.eloquent.raft.EloquentRaftProto.RaftMessage.ContentsCase getContentsCase(); } /** * <pre> ** * A common class for all sorts of Raft requests, wrapped in relevant * metadata. * </pre> * * Protobuf type {@code ai.eloquent.raft.RaftMessage} */ public static final class RaftMessage extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.RaftMessage) RaftMessageOrBuilder { private static final long serialVersionUID = 0L; // Use RaftMessage.newBuilder() to construct. private RaftMessage(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RaftMessage() { isRPC_ = false; sender_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private RaftMessage( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { isRPC_ = input.readBool(); break; } case 18: { ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.Builder subBuilder = null; if (contentsCase_ == 2) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 2; break; } case 26: { ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.Builder subBuilder = null; if (contentsCase_ == 3) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 3; break; } case 34: { ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.Builder subBuilder = null; if (contentsCase_ == 4) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 4; break; } case 42: { ai.eloquent.raft.EloquentRaftProto.AddServerRequest.Builder subBuilder = null; if (contentsCase_ == 5) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.AddServerRequest) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.AddServerRequest.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.AddServerRequest) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 5; break; } case 50: { ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.Builder subBuilder = null; if (contentsCase_ == 6) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 6; break; } case 58: { ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.Builder subBuilder = null; if (contentsCase_ == 7) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 7; break; } case 66: { ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.Builder subBuilder = null; if (contentsCase_ == 8) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 8; break; } case 74: { ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.Builder subBuilder = null; if (contentsCase_ == 9) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 9; break; } case 82: { ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.Builder subBuilder = null; if (contentsCase_ == 10) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 10; break; } case 90: { ai.eloquent.raft.EloquentRaftProto.AddServerReply.Builder subBuilder = null; if (contentsCase_ == 11) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.AddServerReply) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.AddServerReply.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.AddServerReply) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 11; break; } case 98: { ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.Builder subBuilder = null; if (contentsCase_ == 12) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 12; break; } case 106: { ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.Builder subBuilder = null; if (contentsCase_ == 13) { subBuilder = ((ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) contents_).toBuilder(); } contents_ = input.readMessage(ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) contents_); contents_ = subBuilder.buildPartial(); } contentsCase_ = 13; break; } case 114: { java.lang.String s = input.readStringRequireUtf8(); sender_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RaftMessage_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RaftMessage_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.RaftMessage.class, ai.eloquent.raft.EloquentRaftProto.RaftMessage.Builder.class); } private int contentsCase_ = 0; private java.lang.Object contents_; public enum ContentsCase implements com.google.protobuf.Internal.EnumLite { APPENDENTRIES(2), REQUESTVOTES(3), APPLYTRANSITION(4), ADDSERVER(5), REMOVESERVER(6), INSTALLSNAPSHOT(7), APPENDENTRIESREPLY(8), REQUESTVOTESREPLY(9), APPLYTRANSITIONREPLY(10), ADDSERVERREPLY(11), REMOVESERVERREPLY(12), INSTALLSNAPSHOTREPLY(13), CONTENTS_NOT_SET(0); private final int value; private ContentsCase(int value) { this.value = value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static ContentsCase valueOf(int value) { return forNumber(value); } public static ContentsCase forNumber(int value) { switch (value) { case 2: return APPENDENTRIES; case 3: return REQUESTVOTES; case 4: return APPLYTRANSITION; case 5: return ADDSERVER; case 6: return REMOVESERVER; case 7: return INSTALLSNAPSHOT; case 8: return APPENDENTRIESREPLY; case 9: return REQUESTVOTESREPLY; case 10: return APPLYTRANSITIONREPLY; case 11: return ADDSERVERREPLY; case 12: return REMOVESERVERREPLY; case 13: return INSTALLSNAPSHOTREPLY; case 0: return CONTENTS_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public ContentsCase getContentsCase() { return ContentsCase.forNumber( contentsCase_); } public static final int ISRPC_FIELD_NUMBER = 1; private boolean isRPC_; /** * <pre> ** If true, we are expecting a response to this request over the RPC channel. * </pre> * * <code>bool isRPC = 1;</code> */ public boolean getIsRPC() { return isRPC_; } public static final int APPENDENTRIES_FIELD_NUMBER = 2; /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public boolean hasAppendEntries() { return contentsCase_ == 2; } /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest getAppendEntries() { if (contentsCase_ == 2) { return (ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.getDefaultInstance(); } /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequestOrBuilder getAppendEntriesOrBuilder() { if (contentsCase_ == 2) { return (ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.getDefaultInstance(); } public static final int REQUESTVOTES_FIELD_NUMBER = 3; /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public boolean hasRequestVotes() { return contentsCase_ == 3; } /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest getRequestVotes() { if (contentsCase_ == 3) { return (ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public ai.eloquent.raft.EloquentRaftProto.RequestVoteRequestOrBuilder getRequestVotesOrBuilder() { if (contentsCase_ == 3) { return (ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.getDefaultInstance(); } public static final int APPLYTRANSITION_FIELD_NUMBER = 4; /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public boolean hasApplyTransition() { return contentsCase_ == 4; } /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest getApplyTransition() { if (contentsCase_ == 4) { return (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequestOrBuilder getApplyTransitionOrBuilder() { if (contentsCase_ == 4) { return (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.getDefaultInstance(); } public static final int ADDSERVER_FIELD_NUMBER = 5; /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public boolean hasAddServer() { return contentsCase_ == 5; } /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.AddServerRequest getAddServer() { if (contentsCase_ == 5) { return (ai.eloquent.raft.EloquentRaftProto.AddServerRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.AddServerRequest.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.AddServerRequestOrBuilder getAddServerOrBuilder() { if (contentsCase_ == 5) { return (ai.eloquent.raft.EloquentRaftProto.AddServerRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.AddServerRequest.getDefaultInstance(); } public static final int REMOVESERVER_FIELD_NUMBER = 6; /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public boolean hasRemoveServer() { return contentsCase_ == 6; } /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest getRemoveServer() { if (contentsCase_ == 6) { return (ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public ai.eloquent.raft.EloquentRaftProto.RemoveServerRequestOrBuilder getRemoveServerOrBuilder() { if (contentsCase_ == 6) { return (ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.getDefaultInstance(); } public static final int INSTALLSNAPSHOT_FIELD_NUMBER = 7; /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public boolean hasInstallSnapshot() { return contentsCase_ == 7; } /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest getInstallSnapshot() { if (contentsCase_ == 7) { return (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequestOrBuilder getInstallSnapshotOrBuilder() { if (contentsCase_ == 7) { return (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.getDefaultInstance(); } public static final int APPENDENTRIESREPLY_FIELD_NUMBER = 8; /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public boolean hasAppendEntriesReply() { return contentsCase_ == 8; } /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply getAppendEntriesReply() { if (contentsCase_ == 8) { return (ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.getDefaultInstance(); } /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public ai.eloquent.raft.EloquentRaftProto.AppendEntriesReplyOrBuilder getAppendEntriesReplyOrBuilder() { if (contentsCase_ == 8) { return (ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.getDefaultInstance(); } public static final int REQUESTVOTESREPLY_FIELD_NUMBER = 9; /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public boolean hasRequestVotesReply() { return contentsCase_ == 9; } /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public ai.eloquent.raft.EloquentRaftProto.RequestVoteReply getRequestVotesReply() { if (contentsCase_ == 9) { return (ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public ai.eloquent.raft.EloquentRaftProto.RequestVoteReplyOrBuilder getRequestVotesReplyOrBuilder() { if (contentsCase_ == 9) { return (ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.getDefaultInstance(); } public static final int APPLYTRANSITIONREPLY_FIELD_NUMBER = 10; /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public boolean hasApplyTransitionReply() { return contentsCase_ == 10; } /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply getApplyTransitionReply() { if (contentsCase_ == 10) { return (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReplyOrBuilder getApplyTransitionReplyOrBuilder() { if (contentsCase_ == 10) { return (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.getDefaultInstance(); } public static final int ADDSERVERREPLY_FIELD_NUMBER = 11; /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public boolean hasAddServerReply() { return contentsCase_ == 11; } /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public ai.eloquent.raft.EloquentRaftProto.AddServerReply getAddServerReply() { if (contentsCase_ == 11) { return (ai.eloquent.raft.EloquentRaftProto.AddServerReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.AddServerReply.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public ai.eloquent.raft.EloquentRaftProto.AddServerReplyOrBuilder getAddServerReplyOrBuilder() { if (contentsCase_ == 11) { return (ai.eloquent.raft.EloquentRaftProto.AddServerReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.AddServerReply.getDefaultInstance(); } public static final int REMOVESERVERREPLY_FIELD_NUMBER = 12; /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public boolean hasRemoveServerReply() { return contentsCase_ == 12; } /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public ai.eloquent.raft.EloquentRaftProto.RemoveServerReply getRemoveServerReply() { if (contentsCase_ == 12) { return (ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public ai.eloquent.raft.EloquentRaftProto.RemoveServerReplyOrBuilder getRemoveServerReplyOrBuilder() { if (contentsCase_ == 12) { return (ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.getDefaultInstance(); } public static final int INSTALLSNAPSHOTREPLY_FIELD_NUMBER = 13; /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public boolean hasInstallSnapshotReply() { return contentsCase_ == 13; } /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply getInstallSnapshotReply() { if (contentsCase_ == 13) { return (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReplyOrBuilder getInstallSnapshotReplyOrBuilder() { if (contentsCase_ == 13) { return (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.getDefaultInstance(); } public static final int SENDER_FIELD_NUMBER = 14; private volatile java.lang.Object sender_; /** * <pre> ** The name of the node that sent this message. * </pre> * * <code>string sender = 14;</code> */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } } /** * <pre> ** The name of the node that sent this message. * </pre> * * <code>string sender = 14;</code> */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (isRPC_ != false) { output.writeBool(1, isRPC_); } if (contentsCase_ == 2) { output.writeMessage(2, (ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) contents_); } if (contentsCase_ == 3) { output.writeMessage(3, (ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) contents_); } if (contentsCase_ == 4) { output.writeMessage(4, (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) contents_); } if (contentsCase_ == 5) { output.writeMessage(5, (ai.eloquent.raft.EloquentRaftProto.AddServerRequest) contents_); } if (contentsCase_ == 6) { output.writeMessage(6, (ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) contents_); } if (contentsCase_ == 7) { output.writeMessage(7, (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) contents_); } if (contentsCase_ == 8) { output.writeMessage(8, (ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) contents_); } if (contentsCase_ == 9) { output.writeMessage(9, (ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) contents_); } if (contentsCase_ == 10) { output.writeMessage(10, (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) contents_); } if (contentsCase_ == 11) { output.writeMessage(11, (ai.eloquent.raft.EloquentRaftProto.AddServerReply) contents_); } if (contentsCase_ == 12) { output.writeMessage(12, (ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) contents_); } if (contentsCase_ == 13) { output.writeMessage(13, (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) contents_); } if (!getSenderBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 14, sender_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (isRPC_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(1, isRPC_); } if (contentsCase_ == 2) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, (ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) contents_); } if (contentsCase_ == 3) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, (ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) contents_); } if (contentsCase_ == 4) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) contents_); } if (contentsCase_ == 5) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, (ai.eloquent.raft.EloquentRaftProto.AddServerRequest) contents_); } if (contentsCase_ == 6) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(6, (ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) contents_); } if (contentsCase_ == 7) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(7, (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) contents_); } if (contentsCase_ == 8) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(8, (ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) contents_); } if (contentsCase_ == 9) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(9, (ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) contents_); } if (contentsCase_ == 10) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(10, (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) contents_); } if (contentsCase_ == 11) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(11, (ai.eloquent.raft.EloquentRaftProto.AddServerReply) contents_); } if (contentsCase_ == 12) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(12, (ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) contents_); } if (contentsCase_ == 13) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(13, (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) contents_); } if (!getSenderBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(14, sender_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.RaftMessage)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.RaftMessage other = (ai.eloquent.raft.EloquentRaftProto.RaftMessage) obj; boolean result = true; result = result && (getIsRPC() == other.getIsRPC()); result = result && getSender() .equals(other.getSender()); result = result && getContentsCase().equals( other.getContentsCase()); if (!result) return false; switch (contentsCase_) { case 2: result = result && getAppendEntries() .equals(other.getAppendEntries()); break; case 3: result = result && getRequestVotes() .equals(other.getRequestVotes()); break; case 4: result = result && getApplyTransition() .equals(other.getApplyTransition()); break; case 5: result = result && getAddServer() .equals(other.getAddServer()); break; case 6: result = result && getRemoveServer() .equals(other.getRemoveServer()); break; case 7: result = result && getInstallSnapshot() .equals(other.getInstallSnapshot()); break; case 8: result = result && getAppendEntriesReply() .equals(other.getAppendEntriesReply()); break; case 9: result = result && getRequestVotesReply() .equals(other.getRequestVotesReply()); break; case 10: result = result && getApplyTransitionReply() .equals(other.getApplyTransitionReply()); break; case 11: result = result && getAddServerReply() .equals(other.getAddServerReply()); break; case 12: result = result && getRemoveServerReply() .equals(other.getRemoveServerReply()); break; case 13: result = result && getInstallSnapshotReply() .equals(other.getInstallSnapshotReply()); break; case 0: default: } result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ISRPC_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getIsRPC()); hash = (37 * hash) + SENDER_FIELD_NUMBER; hash = (53 * hash) + getSender().hashCode(); switch (contentsCase_) { case 2: hash = (37 * hash) + APPENDENTRIES_FIELD_NUMBER; hash = (53 * hash) + getAppendEntries().hashCode(); break; case 3: hash = (37 * hash) + REQUESTVOTES_FIELD_NUMBER; hash = (53 * hash) + getRequestVotes().hashCode(); break; case 4: hash = (37 * hash) + APPLYTRANSITION_FIELD_NUMBER; hash = (53 * hash) + getApplyTransition().hashCode(); break; case 5: hash = (37 * hash) + ADDSERVER_FIELD_NUMBER; hash = (53 * hash) + getAddServer().hashCode(); break; case 6: hash = (37 * hash) + REMOVESERVER_FIELD_NUMBER; hash = (53 * hash) + getRemoveServer().hashCode(); break; case 7: hash = (37 * hash) + INSTALLSNAPSHOT_FIELD_NUMBER; hash = (53 * hash) + getInstallSnapshot().hashCode(); break; case 8: hash = (37 * hash) + APPENDENTRIESREPLY_FIELD_NUMBER; hash = (53 * hash) + getAppendEntriesReply().hashCode(); break; case 9: hash = (37 * hash) + REQUESTVOTESREPLY_FIELD_NUMBER; hash = (53 * hash) + getRequestVotesReply().hashCode(); break; case 10: hash = (37 * hash) + APPLYTRANSITIONREPLY_FIELD_NUMBER; hash = (53 * hash) + getApplyTransitionReply().hashCode(); break; case 11: hash = (37 * hash) + ADDSERVERREPLY_FIELD_NUMBER; hash = (53 * hash) + getAddServerReply().hashCode(); break; case 12: hash = (37 * hash) + REMOVESERVERREPLY_FIELD_NUMBER; hash = (53 * hash) + getRemoveServerReply().hashCode(); break; case 13: hash = (37 * hash) + INSTALLSNAPSHOTREPLY_FIELD_NUMBER; hash = (53 * hash) + getInstallSnapshotReply().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.RaftMessage prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> ** * A common class for all sorts of Raft requests, wrapped in relevant * metadata. * </pre> * * Protobuf type {@code ai.eloquent.raft.RaftMessage} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.RaftMessage) ai.eloquent.raft.EloquentRaftProto.RaftMessageOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RaftMessage_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RaftMessage_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.RaftMessage.class, ai.eloquent.raft.EloquentRaftProto.RaftMessage.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.RaftMessage.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); isRPC_ = false; sender_ = ""; contentsCase_ = 0; contents_ = null; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RaftMessage_descriptor; } public ai.eloquent.raft.EloquentRaftProto.RaftMessage getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.RaftMessage.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.RaftMessage build() { ai.eloquent.raft.EloquentRaftProto.RaftMessage result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.RaftMessage buildPartial() { ai.eloquent.raft.EloquentRaftProto.RaftMessage result = new ai.eloquent.raft.EloquentRaftProto.RaftMessage(this); result.isRPC_ = isRPC_; if (contentsCase_ == 2) { if (appendEntriesBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = appendEntriesBuilder_.build(); } } if (contentsCase_ == 3) { if (requestVotesBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = requestVotesBuilder_.build(); } } if (contentsCase_ == 4) { if (applyTransitionBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = applyTransitionBuilder_.build(); } } if (contentsCase_ == 5) { if (addServerBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = addServerBuilder_.build(); } } if (contentsCase_ == 6) { if (removeServerBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = removeServerBuilder_.build(); } } if (contentsCase_ == 7) { if (installSnapshotBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = installSnapshotBuilder_.build(); } } if (contentsCase_ == 8) { if (appendEntriesReplyBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = appendEntriesReplyBuilder_.build(); } } if (contentsCase_ == 9) { if (requestVotesReplyBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = requestVotesReplyBuilder_.build(); } } if (contentsCase_ == 10) { if (applyTransitionReplyBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = applyTransitionReplyBuilder_.build(); } } if (contentsCase_ == 11) { if (addServerReplyBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = addServerReplyBuilder_.build(); } } if (contentsCase_ == 12) { if (removeServerReplyBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = removeServerReplyBuilder_.build(); } } if (contentsCase_ == 13) { if (installSnapshotReplyBuilder_ == null) { result.contents_ = contents_; } else { result.contents_ = installSnapshotReplyBuilder_.build(); } } result.sender_ = sender_; result.contentsCase_ = contentsCase_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.RaftMessage) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.RaftMessage)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.RaftMessage other) { if (other == ai.eloquent.raft.EloquentRaftProto.RaftMessage.getDefaultInstance()) return this; if (other.getIsRPC() != false) { setIsRPC(other.getIsRPC()); } if (!other.getSender().isEmpty()) { sender_ = other.sender_; onChanged(); } switch (other.getContentsCase()) { case APPENDENTRIES: { mergeAppendEntries(other.getAppendEntries()); break; } case REQUESTVOTES: { mergeRequestVotes(other.getRequestVotes()); break; } case APPLYTRANSITION: { mergeApplyTransition(other.getApplyTransition()); break; } case ADDSERVER: { mergeAddServer(other.getAddServer()); break; } case REMOVESERVER: { mergeRemoveServer(other.getRemoveServer()); break; } case INSTALLSNAPSHOT: { mergeInstallSnapshot(other.getInstallSnapshot()); break; } case APPENDENTRIESREPLY: { mergeAppendEntriesReply(other.getAppendEntriesReply()); break; } case REQUESTVOTESREPLY: { mergeRequestVotesReply(other.getRequestVotesReply()); break; } case APPLYTRANSITIONREPLY: { mergeApplyTransitionReply(other.getApplyTransitionReply()); break; } case ADDSERVERREPLY: { mergeAddServerReply(other.getAddServerReply()); break; } case REMOVESERVERREPLY: { mergeRemoveServerReply(other.getRemoveServerReply()); break; } case INSTALLSNAPSHOTREPLY: { mergeInstallSnapshotReply(other.getInstallSnapshotReply()); break; } case CONTENTS_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.RaftMessage parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.RaftMessage) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int contentsCase_ = 0; private java.lang.Object contents_; public ContentsCase getContentsCase() { return ContentsCase.forNumber( contentsCase_); } public Builder clearContents() { contentsCase_ = 0; contents_ = null; onChanged(); return this; } private boolean isRPC_ ; /** * <pre> ** If true, we are expecting a response to this request over the RPC channel. * </pre> * * <code>bool isRPC = 1;</code> */ public boolean getIsRPC() { return isRPC_; } /** * <pre> ** If true, we are expecting a response to this request over the RPC channel. * </pre> * * <code>bool isRPC = 1;</code> */ public Builder setIsRPC(boolean value) { isRPC_ = value; onChanged(); return this; } /** * <pre> ** If true, we are expecting a response to this request over the RPC channel. * </pre> * * <code>bool isRPC = 1;</code> */ public Builder clearIsRPC() { isRPC_ = false; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest, ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.Builder, ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequestOrBuilder> appendEntriesBuilder_; /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public boolean hasAppendEntries() { return contentsCase_ == 2; } /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest getAppendEntries() { if (appendEntriesBuilder_ == null) { if (contentsCase_ == 2) { return (ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.getDefaultInstance(); } else { if (contentsCase_ == 2) { return appendEntriesBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.getDefaultInstance(); } } /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public Builder setAppendEntries(ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest value) { if (appendEntriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { appendEntriesBuilder_.setMessage(value); } contentsCase_ = 2; return this; } /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public Builder setAppendEntries( ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.Builder builderForValue) { if (appendEntriesBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { appendEntriesBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 2; return this; } /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public Builder mergeAppendEntries(ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest value) { if (appendEntriesBuilder_ == null) { if (contentsCase_ == 2 && contents_ != ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.newBuilder((ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 2) { appendEntriesBuilder_.mergeFrom(value); } appendEntriesBuilder_.setMessage(value); } contentsCase_ = 2; return this; } /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public Builder clearAppendEntries() { if (appendEntriesBuilder_ == null) { if (contentsCase_ == 2) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 2) { contentsCase_ = 0; contents_ = null; } appendEntriesBuilder_.clear(); } return this; } /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.Builder getAppendEntriesBuilder() { return getAppendEntriesFieldBuilder().getBuilder(); } /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ public ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequestOrBuilder getAppendEntriesOrBuilder() { if ((contentsCase_ == 2) && (appendEntriesBuilder_ != null)) { return appendEntriesBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 2) { return (ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.getDefaultInstance(); } } /** * <pre> * -- The Requests * </pre> * * <code>.ai.eloquent.raft.AppendEntriesRequest appendEntries = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest, ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.Builder, ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequestOrBuilder> getAppendEntriesFieldBuilder() { if (appendEntriesBuilder_ == null) { if (!(contentsCase_ == 2)) { contents_ = ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.getDefaultInstance(); } appendEntriesBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest, ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.Builder, ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequestOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 2; onChanged();; return appendEntriesBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest, ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.Builder, ai.eloquent.raft.EloquentRaftProto.RequestVoteRequestOrBuilder> requestVotesBuilder_; /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public boolean hasRequestVotes() { return contentsCase_ == 3; } /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest getRequestVotes() { if (requestVotesBuilder_ == null) { if (contentsCase_ == 3) { return (ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.getDefaultInstance(); } else { if (contentsCase_ == 3) { return requestVotesBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public Builder setRequestVotes(ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest value) { if (requestVotesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { requestVotesBuilder_.setMessage(value); } contentsCase_ = 3; return this; } /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public Builder setRequestVotes( ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.Builder builderForValue) { if (requestVotesBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { requestVotesBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 3; return this; } /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public Builder mergeRequestVotes(ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest value) { if (requestVotesBuilder_ == null) { if (contentsCase_ == 3 && contents_ != ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.newBuilder((ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 3) { requestVotesBuilder_.mergeFrom(value); } requestVotesBuilder_.setMessage(value); } contentsCase_ = 3; return this; } /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public Builder clearRequestVotes() { if (requestVotesBuilder_ == null) { if (contentsCase_ == 3) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 3) { contentsCase_ = 0; contents_ = null; } requestVotesBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.Builder getRequestVotesBuilder() { return getRequestVotesFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ public ai.eloquent.raft.EloquentRaftProto.RequestVoteRequestOrBuilder getRequestVotesOrBuilder() { if ((contentsCase_ == 3) && (requestVotesBuilder_ != null)) { return requestVotesBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 3) { return (ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RequestVoteRequest requestVotes = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest, ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.Builder, ai.eloquent.raft.EloquentRaftProto.RequestVoteRequestOrBuilder> getRequestVotesFieldBuilder() { if (requestVotesBuilder_ == null) { if (!(contentsCase_ == 3)) { contents_ = ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.getDefaultInstance(); } requestVotesBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest, ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.Builder, ai.eloquent.raft.EloquentRaftProto.RequestVoteRequestOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 3; onChanged();; return requestVotesBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.Builder, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequestOrBuilder> applyTransitionBuilder_; /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public boolean hasApplyTransition() { return contentsCase_ == 4; } /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest getApplyTransition() { if (applyTransitionBuilder_ == null) { if (contentsCase_ == 4) { return (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.getDefaultInstance(); } else { if (contentsCase_ == 4) { return applyTransitionBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public Builder setApplyTransition(ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest value) { if (applyTransitionBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { applyTransitionBuilder_.setMessage(value); } contentsCase_ = 4; return this; } /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public Builder setApplyTransition( ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.Builder builderForValue) { if (applyTransitionBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { applyTransitionBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 4; return this; } /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public Builder mergeApplyTransition(ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest value) { if (applyTransitionBuilder_ == null) { if (contentsCase_ == 4 && contents_ != ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.newBuilder((ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 4) { applyTransitionBuilder_.mergeFrom(value); } applyTransitionBuilder_.setMessage(value); } contentsCase_ = 4; return this; } /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public Builder clearApplyTransition() { if (applyTransitionBuilder_ == null) { if (contentsCase_ == 4) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 4) { contentsCase_ = 0; contents_ = null; } applyTransitionBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.Builder getApplyTransitionBuilder() { return getApplyTransitionFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequestOrBuilder getApplyTransitionOrBuilder() { if ((contentsCase_ == 4) && (applyTransitionBuilder_ != null)) { return applyTransitionBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 4) { return (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.ApplyTransitionRequest applyTransition = 4;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.Builder, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequestOrBuilder> getApplyTransitionFieldBuilder() { if (applyTransitionBuilder_ == null) { if (!(contentsCase_ == 4)) { contents_ = ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.getDefaultInstance(); } applyTransitionBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.Builder, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequestOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 4; onChanged();; return applyTransitionBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AddServerRequest, ai.eloquent.raft.EloquentRaftProto.AddServerRequest.Builder, ai.eloquent.raft.EloquentRaftProto.AddServerRequestOrBuilder> addServerBuilder_; /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public boolean hasAddServer() { return contentsCase_ == 5; } /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.AddServerRequest getAddServer() { if (addServerBuilder_ == null) { if (contentsCase_ == 5) { return (ai.eloquent.raft.EloquentRaftProto.AddServerRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.AddServerRequest.getDefaultInstance(); } else { if (contentsCase_ == 5) { return addServerBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.AddServerRequest.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public Builder setAddServer(ai.eloquent.raft.EloquentRaftProto.AddServerRequest value) { if (addServerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { addServerBuilder_.setMessage(value); } contentsCase_ = 5; return this; } /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public Builder setAddServer( ai.eloquent.raft.EloquentRaftProto.AddServerRequest.Builder builderForValue) { if (addServerBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { addServerBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 5; return this; } /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public Builder mergeAddServer(ai.eloquent.raft.EloquentRaftProto.AddServerRequest value) { if (addServerBuilder_ == null) { if (contentsCase_ == 5 && contents_ != ai.eloquent.raft.EloquentRaftProto.AddServerRequest.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.AddServerRequest.newBuilder((ai.eloquent.raft.EloquentRaftProto.AddServerRequest) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 5) { addServerBuilder_.mergeFrom(value); } addServerBuilder_.setMessage(value); } contentsCase_ = 5; return this; } /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public Builder clearAddServer() { if (addServerBuilder_ == null) { if (contentsCase_ == 5) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 5) { contentsCase_ = 0; contents_ = null; } addServerBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.AddServerRequest.Builder getAddServerBuilder() { return getAddServerFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.AddServerRequestOrBuilder getAddServerOrBuilder() { if ((contentsCase_ == 5) && (addServerBuilder_ != null)) { return addServerBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 5) { return (ai.eloquent.raft.EloquentRaftProto.AddServerRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.AddServerRequest.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.AddServerRequest addServer = 5;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AddServerRequest, ai.eloquent.raft.EloquentRaftProto.AddServerRequest.Builder, ai.eloquent.raft.EloquentRaftProto.AddServerRequestOrBuilder> getAddServerFieldBuilder() { if (addServerBuilder_ == null) { if (!(contentsCase_ == 5)) { contents_ = ai.eloquent.raft.EloquentRaftProto.AddServerRequest.getDefaultInstance(); } addServerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AddServerRequest, ai.eloquent.raft.EloquentRaftProto.AddServerRequest.Builder, ai.eloquent.raft.EloquentRaftProto.AddServerRequestOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.AddServerRequest) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 5; onChanged();; return addServerBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest, ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.Builder, ai.eloquent.raft.EloquentRaftProto.RemoveServerRequestOrBuilder> removeServerBuilder_; /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public boolean hasRemoveServer() { return contentsCase_ == 6; } /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest getRemoveServer() { if (removeServerBuilder_ == null) { if (contentsCase_ == 6) { return (ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.getDefaultInstance(); } else { if (contentsCase_ == 6) { return removeServerBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public Builder setRemoveServer(ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest value) { if (removeServerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { removeServerBuilder_.setMessage(value); } contentsCase_ = 6; return this; } /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public Builder setRemoveServer( ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.Builder builderForValue) { if (removeServerBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { removeServerBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 6; return this; } /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public Builder mergeRemoveServer(ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest value) { if (removeServerBuilder_ == null) { if (contentsCase_ == 6 && contents_ != ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.newBuilder((ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 6) { removeServerBuilder_.mergeFrom(value); } removeServerBuilder_.setMessage(value); } contentsCase_ = 6; return this; } /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public Builder clearRemoveServer() { if (removeServerBuilder_ == null) { if (contentsCase_ == 6) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 6) { contentsCase_ = 0; contents_ = null; } removeServerBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.Builder getRemoveServerBuilder() { return getRemoveServerFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ public ai.eloquent.raft.EloquentRaftProto.RemoveServerRequestOrBuilder getRemoveServerOrBuilder() { if ((contentsCase_ == 6) && (removeServerBuilder_ != null)) { return removeServerBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 6) { return (ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RemoveServerRequest removeServer = 6;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest, ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.Builder, ai.eloquent.raft.EloquentRaftProto.RemoveServerRequestOrBuilder> getRemoveServerFieldBuilder() { if (removeServerBuilder_ == null) { if (!(contentsCase_ == 6)) { contents_ = ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.getDefaultInstance(); } removeServerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest, ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.Builder, ai.eloquent.raft.EloquentRaftProto.RemoveServerRequestOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 6; onChanged();; return removeServerBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.Builder, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequestOrBuilder> installSnapshotBuilder_; /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public boolean hasInstallSnapshot() { return contentsCase_ == 7; } /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest getInstallSnapshot() { if (installSnapshotBuilder_ == null) { if (contentsCase_ == 7) { return (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.getDefaultInstance(); } else { if (contentsCase_ == 7) { return installSnapshotBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public Builder setInstallSnapshot(ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest value) { if (installSnapshotBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { installSnapshotBuilder_.setMessage(value); } contentsCase_ = 7; return this; } /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public Builder setInstallSnapshot( ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.Builder builderForValue) { if (installSnapshotBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { installSnapshotBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 7; return this; } /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public Builder mergeInstallSnapshot(ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest value) { if (installSnapshotBuilder_ == null) { if (contentsCase_ == 7 && contents_ != ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.newBuilder((ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 7) { installSnapshotBuilder_.mergeFrom(value); } installSnapshotBuilder_.setMessage(value); } contentsCase_ = 7; return this; } /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public Builder clearInstallSnapshot() { if (installSnapshotBuilder_ == null) { if (contentsCase_ == 7) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 7) { contentsCase_ = 0; contents_ = null; } installSnapshotBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.Builder getInstallSnapshotBuilder() { return getInstallSnapshotFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequestOrBuilder getInstallSnapshotOrBuilder() { if ((contentsCase_ == 7) && (installSnapshotBuilder_ != null)) { return installSnapshotBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 7) { return (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) contents_; } return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.InstallSnapshotRequest installSnapshot = 7;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.Builder, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequestOrBuilder> getInstallSnapshotFieldBuilder() { if (installSnapshotBuilder_ == null) { if (!(contentsCase_ == 7)) { contents_ = ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.getDefaultInstance(); } installSnapshotBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.Builder, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequestOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 7; onChanged();; return installSnapshotBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply, ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.Builder, ai.eloquent.raft.EloquentRaftProto.AppendEntriesReplyOrBuilder> appendEntriesReplyBuilder_; /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public boolean hasAppendEntriesReply() { return contentsCase_ == 8; } /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply getAppendEntriesReply() { if (appendEntriesReplyBuilder_ == null) { if (contentsCase_ == 8) { return (ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.getDefaultInstance(); } else { if (contentsCase_ == 8) { return appendEntriesReplyBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.getDefaultInstance(); } } /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public Builder setAppendEntriesReply(ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply value) { if (appendEntriesReplyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { appendEntriesReplyBuilder_.setMessage(value); } contentsCase_ = 8; return this; } /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public Builder setAppendEntriesReply( ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.Builder builderForValue) { if (appendEntriesReplyBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { appendEntriesReplyBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 8; return this; } /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public Builder mergeAppendEntriesReply(ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply value) { if (appendEntriesReplyBuilder_ == null) { if (contentsCase_ == 8 && contents_ != ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.newBuilder((ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 8) { appendEntriesReplyBuilder_.mergeFrom(value); } appendEntriesReplyBuilder_.setMessage(value); } contentsCase_ = 8; return this; } /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public Builder clearAppendEntriesReply() { if (appendEntriesReplyBuilder_ == null) { if (contentsCase_ == 8) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 8) { contentsCase_ = 0; contents_ = null; } appendEntriesReplyBuilder_.clear(); } return this; } /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.Builder getAppendEntriesReplyBuilder() { return getAppendEntriesReplyFieldBuilder().getBuilder(); } /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ public ai.eloquent.raft.EloquentRaftProto.AppendEntriesReplyOrBuilder getAppendEntriesReplyOrBuilder() { if ((contentsCase_ == 8) && (appendEntriesReplyBuilder_ != null)) { return appendEntriesReplyBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 8) { return (ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.getDefaultInstance(); } } /** * <pre> * -- The Replies * </pre> * * <code>.ai.eloquent.raft.AppendEntriesReply appendEntriesReply = 8;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply, ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.Builder, ai.eloquent.raft.EloquentRaftProto.AppendEntriesReplyOrBuilder> getAppendEntriesReplyFieldBuilder() { if (appendEntriesReplyBuilder_ == null) { if (!(contentsCase_ == 8)) { contents_ = ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.getDefaultInstance(); } appendEntriesReplyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply, ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.Builder, ai.eloquent.raft.EloquentRaftProto.AppendEntriesReplyOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 8; onChanged();; return appendEntriesReplyBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RequestVoteReply, ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.Builder, ai.eloquent.raft.EloquentRaftProto.RequestVoteReplyOrBuilder> requestVotesReplyBuilder_; /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public boolean hasRequestVotesReply() { return contentsCase_ == 9; } /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public ai.eloquent.raft.EloquentRaftProto.RequestVoteReply getRequestVotesReply() { if (requestVotesReplyBuilder_ == null) { if (contentsCase_ == 9) { return (ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.getDefaultInstance(); } else { if (contentsCase_ == 9) { return requestVotesReplyBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public Builder setRequestVotesReply(ai.eloquent.raft.EloquentRaftProto.RequestVoteReply value) { if (requestVotesReplyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { requestVotesReplyBuilder_.setMessage(value); } contentsCase_ = 9; return this; } /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public Builder setRequestVotesReply( ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.Builder builderForValue) { if (requestVotesReplyBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { requestVotesReplyBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 9; return this; } /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public Builder mergeRequestVotesReply(ai.eloquent.raft.EloquentRaftProto.RequestVoteReply value) { if (requestVotesReplyBuilder_ == null) { if (contentsCase_ == 9 && contents_ != ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.newBuilder((ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 9) { requestVotesReplyBuilder_.mergeFrom(value); } requestVotesReplyBuilder_.setMessage(value); } contentsCase_ = 9; return this; } /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public Builder clearRequestVotesReply() { if (requestVotesReplyBuilder_ == null) { if (contentsCase_ == 9) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 9) { contentsCase_ = 0; contents_ = null; } requestVotesReplyBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.Builder getRequestVotesReplyBuilder() { return getRequestVotesReplyFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ public ai.eloquent.raft.EloquentRaftProto.RequestVoteReplyOrBuilder getRequestVotesReplyOrBuilder() { if ((contentsCase_ == 9) && (requestVotesReplyBuilder_ != null)) { return requestVotesReplyBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 9) { return (ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RequestVoteReply requestVotesReply = 9;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RequestVoteReply, ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.Builder, ai.eloquent.raft.EloquentRaftProto.RequestVoteReplyOrBuilder> getRequestVotesReplyFieldBuilder() { if (requestVotesReplyBuilder_ == null) { if (!(contentsCase_ == 9)) { contents_ = ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.getDefaultInstance(); } requestVotesReplyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RequestVoteReply, ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.Builder, ai.eloquent.raft.EloquentRaftProto.RequestVoteReplyOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 9; onChanged();; return requestVotesReplyBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.Builder, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReplyOrBuilder> applyTransitionReplyBuilder_; /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public boolean hasApplyTransitionReply() { return contentsCase_ == 10; } /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply getApplyTransitionReply() { if (applyTransitionReplyBuilder_ == null) { if (contentsCase_ == 10) { return (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.getDefaultInstance(); } else { if (contentsCase_ == 10) { return applyTransitionReplyBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public Builder setApplyTransitionReply(ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply value) { if (applyTransitionReplyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { applyTransitionReplyBuilder_.setMessage(value); } contentsCase_ = 10; return this; } /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public Builder setApplyTransitionReply( ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.Builder builderForValue) { if (applyTransitionReplyBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { applyTransitionReplyBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 10; return this; } /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public Builder mergeApplyTransitionReply(ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply value) { if (applyTransitionReplyBuilder_ == null) { if (contentsCase_ == 10 && contents_ != ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.newBuilder((ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 10) { applyTransitionReplyBuilder_.mergeFrom(value); } applyTransitionReplyBuilder_.setMessage(value); } contentsCase_ = 10; return this; } /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public Builder clearApplyTransitionReply() { if (applyTransitionReplyBuilder_ == null) { if (contentsCase_ == 10) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 10) { contentsCase_ = 0; contents_ = null; } applyTransitionReplyBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.Builder getApplyTransitionReplyBuilder() { return getApplyTransitionReplyFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReplyOrBuilder getApplyTransitionReplyOrBuilder() { if ((contentsCase_ == 10) && (applyTransitionReplyBuilder_ != null)) { return applyTransitionReplyBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 10) { return (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.ApplyTransitionReply applyTransitionReply = 10;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.Builder, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReplyOrBuilder> getApplyTransitionReplyFieldBuilder() { if (applyTransitionReplyBuilder_ == null) { if (!(contentsCase_ == 10)) { contents_ = ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.getDefaultInstance(); } applyTransitionReplyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.Builder, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReplyOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 10; onChanged();; return applyTransitionReplyBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AddServerReply, ai.eloquent.raft.EloquentRaftProto.AddServerReply.Builder, ai.eloquent.raft.EloquentRaftProto.AddServerReplyOrBuilder> addServerReplyBuilder_; /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public boolean hasAddServerReply() { return contentsCase_ == 11; } /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public ai.eloquent.raft.EloquentRaftProto.AddServerReply getAddServerReply() { if (addServerReplyBuilder_ == null) { if (contentsCase_ == 11) { return (ai.eloquent.raft.EloquentRaftProto.AddServerReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.AddServerReply.getDefaultInstance(); } else { if (contentsCase_ == 11) { return addServerReplyBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.AddServerReply.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public Builder setAddServerReply(ai.eloquent.raft.EloquentRaftProto.AddServerReply value) { if (addServerReplyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { addServerReplyBuilder_.setMessage(value); } contentsCase_ = 11; return this; } /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public Builder setAddServerReply( ai.eloquent.raft.EloquentRaftProto.AddServerReply.Builder builderForValue) { if (addServerReplyBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { addServerReplyBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 11; return this; } /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public Builder mergeAddServerReply(ai.eloquent.raft.EloquentRaftProto.AddServerReply value) { if (addServerReplyBuilder_ == null) { if (contentsCase_ == 11 && contents_ != ai.eloquent.raft.EloquentRaftProto.AddServerReply.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.AddServerReply.newBuilder((ai.eloquent.raft.EloquentRaftProto.AddServerReply) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 11) { addServerReplyBuilder_.mergeFrom(value); } addServerReplyBuilder_.setMessage(value); } contentsCase_ = 11; return this; } /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public Builder clearAddServerReply() { if (addServerReplyBuilder_ == null) { if (contentsCase_ == 11) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 11) { contentsCase_ = 0; contents_ = null; } addServerReplyBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public ai.eloquent.raft.EloquentRaftProto.AddServerReply.Builder getAddServerReplyBuilder() { return getAddServerReplyFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ public ai.eloquent.raft.EloquentRaftProto.AddServerReplyOrBuilder getAddServerReplyOrBuilder() { if ((contentsCase_ == 11) && (addServerReplyBuilder_ != null)) { return addServerReplyBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 11) { return (ai.eloquent.raft.EloquentRaftProto.AddServerReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.AddServerReply.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.AddServerReply addServerReply = 11;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AddServerReply, ai.eloquent.raft.EloquentRaftProto.AddServerReply.Builder, ai.eloquent.raft.EloquentRaftProto.AddServerReplyOrBuilder> getAddServerReplyFieldBuilder() { if (addServerReplyBuilder_ == null) { if (!(contentsCase_ == 11)) { contents_ = ai.eloquent.raft.EloquentRaftProto.AddServerReply.getDefaultInstance(); } addServerReplyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.AddServerReply, ai.eloquent.raft.EloquentRaftProto.AddServerReply.Builder, ai.eloquent.raft.EloquentRaftProto.AddServerReplyOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.AddServerReply) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 11; onChanged();; return addServerReplyBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RemoveServerReply, ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.Builder, ai.eloquent.raft.EloquentRaftProto.RemoveServerReplyOrBuilder> removeServerReplyBuilder_; /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public boolean hasRemoveServerReply() { return contentsCase_ == 12; } /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public ai.eloquent.raft.EloquentRaftProto.RemoveServerReply getRemoveServerReply() { if (removeServerReplyBuilder_ == null) { if (contentsCase_ == 12) { return (ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.getDefaultInstance(); } else { if (contentsCase_ == 12) { return removeServerReplyBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public Builder setRemoveServerReply(ai.eloquent.raft.EloquentRaftProto.RemoveServerReply value) { if (removeServerReplyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { removeServerReplyBuilder_.setMessage(value); } contentsCase_ = 12; return this; } /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public Builder setRemoveServerReply( ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.Builder builderForValue) { if (removeServerReplyBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { removeServerReplyBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 12; return this; } /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public Builder mergeRemoveServerReply(ai.eloquent.raft.EloquentRaftProto.RemoveServerReply value) { if (removeServerReplyBuilder_ == null) { if (contentsCase_ == 12 && contents_ != ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.newBuilder((ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 12) { removeServerReplyBuilder_.mergeFrom(value); } removeServerReplyBuilder_.setMessage(value); } contentsCase_ = 12; return this; } /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public Builder clearRemoveServerReply() { if (removeServerReplyBuilder_ == null) { if (contentsCase_ == 12) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 12) { contentsCase_ = 0; contents_ = null; } removeServerReplyBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.Builder getRemoveServerReplyBuilder() { return getRemoveServerReplyFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ public ai.eloquent.raft.EloquentRaftProto.RemoveServerReplyOrBuilder getRemoveServerReplyOrBuilder() { if ((contentsCase_ == 12) && (removeServerReplyBuilder_ != null)) { return removeServerReplyBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 12) { return (ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RemoveServerReply removeServerReply = 12;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RemoveServerReply, ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.Builder, ai.eloquent.raft.EloquentRaftProto.RemoveServerReplyOrBuilder> getRemoveServerReplyFieldBuilder() { if (removeServerReplyBuilder_ == null) { if (!(contentsCase_ == 12)) { contents_ = ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.getDefaultInstance(); } removeServerReplyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.RemoveServerReply, ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.Builder, ai.eloquent.raft.EloquentRaftProto.RemoveServerReplyOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 12; onChanged();; return removeServerReplyBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.Builder, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReplyOrBuilder> installSnapshotReplyBuilder_; /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public boolean hasInstallSnapshotReply() { return contentsCase_ == 13; } /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply getInstallSnapshotReply() { if (installSnapshotReplyBuilder_ == null) { if (contentsCase_ == 13) { return (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.getDefaultInstance(); } else { if (contentsCase_ == 13) { return installSnapshotReplyBuilder_.getMessage(); } return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public Builder setInstallSnapshotReply(ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply value) { if (installSnapshotReplyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } contents_ = value; onChanged(); } else { installSnapshotReplyBuilder_.setMessage(value); } contentsCase_ = 13; return this; } /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public Builder setInstallSnapshotReply( ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.Builder builderForValue) { if (installSnapshotReplyBuilder_ == null) { contents_ = builderForValue.build(); onChanged(); } else { installSnapshotReplyBuilder_.setMessage(builderForValue.build()); } contentsCase_ = 13; return this; } /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public Builder mergeInstallSnapshotReply(ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply value) { if (installSnapshotReplyBuilder_ == null) { if (contentsCase_ == 13 && contents_ != ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.getDefaultInstance()) { contents_ = ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.newBuilder((ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) contents_) .mergeFrom(value).buildPartial(); } else { contents_ = value; } onChanged(); } else { if (contentsCase_ == 13) { installSnapshotReplyBuilder_.mergeFrom(value); } installSnapshotReplyBuilder_.setMessage(value); } contentsCase_ = 13; return this; } /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public Builder clearInstallSnapshotReply() { if (installSnapshotReplyBuilder_ == null) { if (contentsCase_ == 13) { contentsCase_ = 0; contents_ = null; onChanged(); } } else { if (contentsCase_ == 13) { contentsCase_ = 0; contents_ = null; } installSnapshotReplyBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.Builder getInstallSnapshotReplyBuilder() { return getInstallSnapshotReplyFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReplyOrBuilder getInstallSnapshotReplyOrBuilder() { if ((contentsCase_ == 13) && (installSnapshotReplyBuilder_ != null)) { return installSnapshotReplyBuilder_.getMessageOrBuilder(); } else { if (contentsCase_ == 13) { return (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) contents_; } return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.InstallSnapshotReply installSnapshotReply = 13;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.Builder, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReplyOrBuilder> getInstallSnapshotReplyFieldBuilder() { if (installSnapshotReplyBuilder_ == null) { if (!(contentsCase_ == 13)) { contents_ = ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.getDefaultInstance(); } installSnapshotReplyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.Builder, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReplyOrBuilder>( (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) contents_, getParentForChildren(), isClean()); contents_ = null; } contentsCase_ = 13; onChanged();; return installSnapshotReplyBuilder_; } private java.lang.Object sender_ = ""; /** * <pre> ** The name of the node that sent this message. * </pre> * * <code>string sender = 14;</code> */ public java.lang.String getSender() { java.lang.Object ref = sender_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sender_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** The name of the node that sent this message. * </pre> * * <code>string sender = 14;</code> */ public com.google.protobuf.ByteString getSenderBytes() { java.lang.Object ref = sender_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sender_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** The name of the node that sent this message. * </pre> * * <code>string sender = 14;</code> */ public Builder setSender( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sender_ = value; onChanged(); return this; } /** * <pre> ** The name of the node that sent this message. * </pre> * * <code>string sender = 14;</code> */ public Builder clearSender() { sender_ = getDefaultInstance().getSender(); onChanged(); return this; } /** * <pre> ** The name of the node that sent this message. * </pre> * * <code>string sender = 14;</code> */ public Builder setSenderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sender_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.RaftMessage) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.RaftMessage) private static final ai.eloquent.raft.EloquentRaftProto.RaftMessage DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.RaftMessage(); } public static ai.eloquent.raft.EloquentRaftProto.RaftMessage getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RaftMessage> PARSER = new com.google.protobuf.AbstractParser<RaftMessage>() { public RaftMessage parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new RaftMessage(input, extensionRegistry); } }; public static com.google.protobuf.Parser<RaftMessage> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RaftMessage> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.RaftMessage getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface AppendEntriesRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.AppendEntriesRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * Leader's term * </pre> * * <code>uint64 term = 1;</code> */ long getTerm(); /** * <pre> * so follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ java.lang.String getLeaderName(); /** * <pre> * so follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ com.google.protobuf.ByteString getLeaderNameBytes(); /** * <pre> * index of log entry immediately preceding new ones * </pre> * * <code>uint64 prevLogIndex = 3;</code> */ long getPrevLogIndex(); /** * <pre> * term of log entry immediately preceding new ones * </pre> * * <code>uint64 prevLogTerm = 4;</code> */ long getPrevLogTerm(); /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ java.util.List<ai.eloquent.raft.EloquentRaftProto.LogEntry> getEntriesList(); /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ ai.eloquent.raft.EloquentRaftProto.LogEntry getEntries(int index); /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ int getEntriesCount(); /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ java.util.List<? extends ai.eloquent.raft.EloquentRaftProto.LogEntryOrBuilder> getEntriesOrBuilderList(); /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ ai.eloquent.raft.EloquentRaftProto.LogEntryOrBuilder getEntriesOrBuilder( int index); /** * <pre> * the leader's commitIndex * </pre> * * <code>uint64 leaderCommit = 6;</code> */ long getLeaderCommit(); /** * <pre> * NOT STANDARD RAFT: the leader's timestamp, so we can compute the timish values across the cluster * </pre> * * <code>uint64 leaderTimish = 7;</code> */ long getLeaderTimish(); } /** * Protobuf type {@code ai.eloquent.raft.AppendEntriesRequest} */ public static final class AppendEntriesRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.AppendEntriesRequest) AppendEntriesRequestOrBuilder { private static final long serialVersionUID = 0L; // Use AppendEntriesRequest.newBuilder() to construct. private AppendEntriesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AppendEntriesRequest() { term_ = 0L; leaderName_ = ""; prevLogIndex_ = 0L; prevLogTerm_ = 0L; entries_ = java.util.Collections.emptyList(); leaderCommit_ = 0L; leaderTimish_ = 0L; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private AppendEntriesRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { term_ = input.readUInt64(); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); leaderName_ = s; break; } case 24: { prevLogIndex_ = input.readUInt64(); break; } case 32: { prevLogTerm_ = input.readUInt64(); break; } case 42: { if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) { entries_ = new java.util.ArrayList<ai.eloquent.raft.EloquentRaftProto.LogEntry>(); mutable_bitField0_ |= 0x00000010; } entries_.add( input.readMessage(ai.eloquent.raft.EloquentRaftProto.LogEntry.parser(), extensionRegistry)); break; } case 48: { leaderCommit_ = input.readUInt64(); break; } case 56: { leaderTimish_ = input.readUInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000010) == 0x00000010)) { entries_ = java.util.Collections.unmodifiableList(entries_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AppendEntriesRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AppendEntriesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.class, ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.Builder.class); } private int bitField0_; public static final int TERM_FIELD_NUMBER = 1; private long term_; /** * <pre> * Leader's term * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } public static final int LEADERNAME_FIELD_NUMBER = 2; private volatile java.lang.Object leaderName_; /** * <pre> * so follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public java.lang.String getLeaderName() { java.lang.Object ref = leaderName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); leaderName_ = s; return s; } } /** * <pre> * so follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public com.google.protobuf.ByteString getLeaderNameBytes() { java.lang.Object ref = leaderName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); leaderName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PREVLOGINDEX_FIELD_NUMBER = 3; private long prevLogIndex_; /** * <pre> * index of log entry immediately preceding new ones * </pre> * * <code>uint64 prevLogIndex = 3;</code> */ public long getPrevLogIndex() { return prevLogIndex_; } public static final int PREVLOGTERM_FIELD_NUMBER = 4; private long prevLogTerm_; /** * <pre> * term of log entry immediately preceding new ones * </pre> * * <code>uint64 prevLogTerm = 4;</code> */ public long getPrevLogTerm() { return prevLogTerm_; } public static final int ENTRIES_FIELD_NUMBER = 5; private java.util.List<ai.eloquent.raft.EloquentRaftProto.LogEntry> entries_; /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public java.util.List<ai.eloquent.raft.EloquentRaftProto.LogEntry> getEntriesList() { return entries_; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public java.util.List<? extends ai.eloquent.raft.EloquentRaftProto.LogEntryOrBuilder> getEntriesOrBuilderList() { return entries_; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public int getEntriesCount() { return entries_.size(); } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.LogEntry getEntries(int index) { return entries_.get(index); } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.LogEntryOrBuilder getEntriesOrBuilder( int index) { return entries_.get(index); } public static final int LEADERCOMMIT_FIELD_NUMBER = 6; private long leaderCommit_; /** * <pre> * the leader's commitIndex * </pre> * * <code>uint64 leaderCommit = 6;</code> */ public long getLeaderCommit() { return leaderCommit_; } public static final int LEADERTIMISH_FIELD_NUMBER = 7; private long leaderTimish_; /** * <pre> * NOT STANDARD RAFT: the leader's timestamp, so we can compute the timish values across the cluster * </pre> * * <code>uint64 leaderTimish = 7;</code> */ public long getLeaderTimish() { return leaderTimish_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (term_ != 0L) { output.writeUInt64(1, term_); } if (!getLeaderNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, leaderName_); } if (prevLogIndex_ != 0L) { output.writeUInt64(3, prevLogIndex_); } if (prevLogTerm_ != 0L) { output.writeUInt64(4, prevLogTerm_); } for (int i = 0; i < entries_.size(); i++) { output.writeMessage(5, entries_.get(i)); } if (leaderCommit_ != 0L) { output.writeUInt64(6, leaderCommit_); } if (leaderTimish_ != 0L) { output.writeUInt64(7, leaderTimish_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (term_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, term_); } if (!getLeaderNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, leaderName_); } if (prevLogIndex_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(3, prevLogIndex_); } if (prevLogTerm_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, prevLogTerm_); } for (int i = 0; i < entries_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, entries_.get(i)); } if (leaderCommit_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(6, leaderCommit_); } if (leaderTimish_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(7, leaderTimish_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest other = (ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) obj; boolean result = true; result = result && (getTerm() == other.getTerm()); result = result && getLeaderName() .equals(other.getLeaderName()); result = result && (getPrevLogIndex() == other.getPrevLogIndex()); result = result && (getPrevLogTerm() == other.getPrevLogTerm()); result = result && getEntriesList() .equals(other.getEntriesList()); result = result && (getLeaderCommit() == other.getLeaderCommit()); result = result && (getLeaderTimish() == other.getLeaderTimish()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTerm()); hash = (37 * hash) + LEADERNAME_FIELD_NUMBER; hash = (53 * hash) + getLeaderName().hashCode(); hash = (37 * hash) + PREVLOGINDEX_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getPrevLogIndex()); hash = (37 * hash) + PREVLOGTERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getPrevLogTerm()); if (getEntriesCount() > 0) { hash = (37 * hash) + ENTRIES_FIELD_NUMBER; hash = (53 * hash) + getEntriesList().hashCode(); } hash = (37 * hash) + LEADERCOMMIT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLeaderCommit()); hash = (37 * hash) + LEADERTIMISH_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLeaderTimish()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.AppendEntriesRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.AppendEntriesRequest) ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AppendEntriesRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AppendEntriesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.class, ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getEntriesFieldBuilder(); } } public Builder clear() { super.clear(); term_ = 0L; leaderName_ = ""; prevLogIndex_ = 0L; prevLogTerm_ = 0L; if (entriesBuilder_ == null) { entries_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { entriesBuilder_.clear(); } leaderCommit_ = 0L; leaderTimish_ = 0L; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AppendEntriesRequest_descriptor; } public ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest build() { ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest buildPartial() { ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest result = new ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.term_ = term_; result.leaderName_ = leaderName_; result.prevLogIndex_ = prevLogIndex_; result.prevLogTerm_ = prevLogTerm_; if (entriesBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { entries_ = java.util.Collections.unmodifiableList(entries_); bitField0_ = (bitField0_ & ~0x00000010); } result.entries_ = entries_; } else { result.entries_ = entriesBuilder_.build(); } result.leaderCommit_ = leaderCommit_; result.leaderTimish_ = leaderTimish_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest other) { if (other == ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest.getDefaultInstance()) return this; if (other.getTerm() != 0L) { setTerm(other.getTerm()); } if (!other.getLeaderName().isEmpty()) { leaderName_ = other.leaderName_; onChanged(); } if (other.getPrevLogIndex() != 0L) { setPrevLogIndex(other.getPrevLogIndex()); } if (other.getPrevLogTerm() != 0L) { setPrevLogTerm(other.getPrevLogTerm()); } if (entriesBuilder_ == null) { if (!other.entries_.isEmpty()) { if (entries_.isEmpty()) { entries_ = other.entries_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureEntriesIsMutable(); entries_.addAll(other.entries_); } onChanged(); } } else { if (!other.entries_.isEmpty()) { if (entriesBuilder_.isEmpty()) { entriesBuilder_.dispose(); entriesBuilder_ = null; entries_ = other.entries_; bitField0_ = (bitField0_ & ~0x00000010); entriesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEntriesFieldBuilder() : null; } else { entriesBuilder_.addAllMessages(other.entries_); } } } if (other.getLeaderCommit() != 0L) { setLeaderCommit(other.getLeaderCommit()); } if (other.getLeaderTimish() != 0L) { setLeaderTimish(other.getLeaderTimish()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long term_ ; /** * <pre> * Leader's term * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } /** * <pre> * Leader's term * </pre> * * <code>uint64 term = 1;</code> */ public Builder setTerm(long value) { term_ = value; onChanged(); return this; } /** * <pre> * Leader's term * </pre> * * <code>uint64 term = 1;</code> */ public Builder clearTerm() { term_ = 0L; onChanged(); return this; } private java.lang.Object leaderName_ = ""; /** * <pre> * so follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public java.lang.String getLeaderName() { java.lang.Object ref = leaderName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); leaderName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * so follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public com.google.protobuf.ByteString getLeaderNameBytes() { java.lang.Object ref = leaderName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); leaderName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * so follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public Builder setLeaderName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } leaderName_ = value; onChanged(); return this; } /** * <pre> * so follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public Builder clearLeaderName() { leaderName_ = getDefaultInstance().getLeaderName(); onChanged(); return this; } /** * <pre> * so follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public Builder setLeaderNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); leaderName_ = value; onChanged(); return this; } private long prevLogIndex_ ; /** * <pre> * index of log entry immediately preceding new ones * </pre> * * <code>uint64 prevLogIndex = 3;</code> */ public long getPrevLogIndex() { return prevLogIndex_; } /** * <pre> * index of log entry immediately preceding new ones * </pre> * * <code>uint64 prevLogIndex = 3;</code> */ public Builder setPrevLogIndex(long value) { prevLogIndex_ = value; onChanged(); return this; } /** * <pre> * index of log entry immediately preceding new ones * </pre> * * <code>uint64 prevLogIndex = 3;</code> */ public Builder clearPrevLogIndex() { prevLogIndex_ = 0L; onChanged(); return this; } private long prevLogTerm_ ; /** * <pre> * term of log entry immediately preceding new ones * </pre> * * <code>uint64 prevLogTerm = 4;</code> */ public long getPrevLogTerm() { return prevLogTerm_; } /** * <pre> * term of log entry immediately preceding new ones * </pre> * * <code>uint64 prevLogTerm = 4;</code> */ public Builder setPrevLogTerm(long value) { prevLogTerm_ = value; onChanged(); return this; } /** * <pre> * term of log entry immediately preceding new ones * </pre> * * <code>uint64 prevLogTerm = 4;</code> */ public Builder clearPrevLogTerm() { prevLogTerm_ = 0L; onChanged(); return this; } private java.util.List<ai.eloquent.raft.EloquentRaftProto.LogEntry> entries_ = java.util.Collections.emptyList(); private void ensureEntriesIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { entries_ = new java.util.ArrayList<ai.eloquent.raft.EloquentRaftProto.LogEntry>(entries_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.LogEntry, ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder, ai.eloquent.raft.EloquentRaftProto.LogEntryOrBuilder> entriesBuilder_; /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public java.util.List<ai.eloquent.raft.EloquentRaftProto.LogEntry> getEntriesList() { if (entriesBuilder_ == null) { return java.util.Collections.unmodifiableList(entries_); } else { return entriesBuilder_.getMessageList(); } } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public int getEntriesCount() { if (entriesBuilder_ == null) { return entries_.size(); } else { return entriesBuilder_.getCount(); } } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.LogEntry getEntries(int index) { if (entriesBuilder_ == null) { return entries_.get(index); } else { return entriesBuilder_.getMessage(index); } } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public Builder setEntries( int index, ai.eloquent.raft.EloquentRaftProto.LogEntry value) { if (entriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntriesIsMutable(); entries_.set(index, value); onChanged(); } else { entriesBuilder_.setMessage(index, value); } return this; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public Builder setEntries( int index, ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder builderForValue) { if (entriesBuilder_ == null) { ensureEntriesIsMutable(); entries_.set(index, builderForValue.build()); onChanged(); } else { entriesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public Builder addEntries(ai.eloquent.raft.EloquentRaftProto.LogEntry value) { if (entriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntriesIsMutable(); entries_.add(value); onChanged(); } else { entriesBuilder_.addMessage(value); } return this; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public Builder addEntries( int index, ai.eloquent.raft.EloquentRaftProto.LogEntry value) { if (entriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntriesIsMutable(); entries_.add(index, value); onChanged(); } else { entriesBuilder_.addMessage(index, value); } return this; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public Builder addEntries( ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder builderForValue) { if (entriesBuilder_ == null) { ensureEntriesIsMutable(); entries_.add(builderForValue.build()); onChanged(); } else { entriesBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public Builder addEntries( int index, ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder builderForValue) { if (entriesBuilder_ == null) { ensureEntriesIsMutable(); entries_.add(index, builderForValue.build()); onChanged(); } else { entriesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public Builder addAllEntries( java.lang.Iterable<? extends ai.eloquent.raft.EloquentRaftProto.LogEntry> values) { if (entriesBuilder_ == null) { ensureEntriesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, entries_); onChanged(); } else { entriesBuilder_.addAllMessages(values); } return this; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public Builder clearEntries() { if (entriesBuilder_ == null) { entries_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { entriesBuilder_.clear(); } return this; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public Builder removeEntries(int index) { if (entriesBuilder_ == null) { ensureEntriesIsMutable(); entries_.remove(index); onChanged(); } else { entriesBuilder_.remove(index); } return this; } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder getEntriesBuilder( int index) { return getEntriesFieldBuilder().getBuilder(index); } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.LogEntryOrBuilder getEntriesOrBuilder( int index) { if (entriesBuilder_ == null) { return entries_.get(index); } else { return entriesBuilder_.getMessageOrBuilder(index); } } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public java.util.List<? extends ai.eloquent.raft.EloquentRaftProto.LogEntryOrBuilder> getEntriesOrBuilderList() { if (entriesBuilder_ != null) { return entriesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(entries_); } } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder addEntriesBuilder() { return getEntriesFieldBuilder().addBuilder( ai.eloquent.raft.EloquentRaftProto.LogEntry.getDefaultInstance()); } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder addEntriesBuilder( int index) { return getEntriesFieldBuilder().addBuilder( index, ai.eloquent.raft.EloquentRaftProto.LogEntry.getDefaultInstance()); } /** * <pre> * log entries to store (empty for heartbeat; may send more than one for efficiency) * </pre> * * <code>repeated .ai.eloquent.raft.LogEntry entries = 5;</code> */ public java.util.List<ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder> getEntriesBuilderList() { return getEntriesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.LogEntry, ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder, ai.eloquent.raft.EloquentRaftProto.LogEntryOrBuilder> getEntriesFieldBuilder() { if (entriesBuilder_ == null) { entriesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.EloquentRaftProto.LogEntry, ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder, ai.eloquent.raft.EloquentRaftProto.LogEntryOrBuilder>( entries_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); entries_ = null; } return entriesBuilder_; } private long leaderCommit_ ; /** * <pre> * the leader's commitIndex * </pre> * * <code>uint64 leaderCommit = 6;</code> */ public long getLeaderCommit() { return leaderCommit_; } /** * <pre> * the leader's commitIndex * </pre> * * <code>uint64 leaderCommit = 6;</code> */ public Builder setLeaderCommit(long value) { leaderCommit_ = value; onChanged(); return this; } /** * <pre> * the leader's commitIndex * </pre> * * <code>uint64 leaderCommit = 6;</code> */ public Builder clearLeaderCommit() { leaderCommit_ = 0L; onChanged(); return this; } private long leaderTimish_ ; /** * <pre> * NOT STANDARD RAFT: the leader's timestamp, so we can compute the timish values across the cluster * </pre> * * <code>uint64 leaderTimish = 7;</code> */ public long getLeaderTimish() { return leaderTimish_; } /** * <pre> * NOT STANDARD RAFT: the leader's timestamp, so we can compute the timish values across the cluster * </pre> * * <code>uint64 leaderTimish = 7;</code> */ public Builder setLeaderTimish(long value) { leaderTimish_ = value; onChanged(); return this; } /** * <pre> * NOT STANDARD RAFT: the leader's timestamp, so we can compute the timish values across the cluster * </pre> * * <code>uint64 leaderTimish = 7;</code> */ public Builder clearLeaderTimish() { leaderTimish_ = 0L; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.AppendEntriesRequest) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.AppendEntriesRequest) private static final ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest(); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AppendEntriesRequest> PARSER = new com.google.protobuf.AbstractParser<AppendEntriesRequest>() { public AppendEntriesRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new AppendEntriesRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<AppendEntriesRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AppendEntriesRequest> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.AppendEntriesRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface AppendEntriesReplyOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.AppendEntriesReply) com.google.protobuf.MessageOrBuilder { /** * <pre> ** currentTerm, for the leader to update itself * </pre> * * <code>uint64 term = 1;</code> */ long getTerm(); /** * <pre> ** true if the follower contained an entry matching prevLogIndex and prevLogTerm * </pre> * * <code>bool success = 2;</code> */ boolean getSuccess(); /** * <pre> ** * The last index replicated on this server. Serves to both signal replication, and * ask for logs starting at a given index. * </pre> * * <code>uint64 nextIndex = 3;</code> */ long getNextIndex(); /** * <pre> ** The name of the follower that sent this reply. * </pre> * * <code>string followerName = 4;</code> */ java.lang.String getFollowerName(); /** * <pre> ** The name of the follower that sent this reply. * </pre> * * <code>string followerName = 4;</code> */ com.google.protobuf.ByteString getFollowerNameBytes(); /** * <pre> ** NOT STANDARD RAFT: If true, this node is not in the quorum, and should perhaps be. * </pre> * * <code>bool missingFromQuorum = 5;</code> */ boolean getMissingFromQuorum(); } /** * Protobuf type {@code ai.eloquent.raft.AppendEntriesReply} */ public static final class AppendEntriesReply extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.AppendEntriesReply) AppendEntriesReplyOrBuilder { private static final long serialVersionUID = 0L; // Use AppendEntriesReply.newBuilder() to construct. private AppendEntriesReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AppendEntriesReply() { term_ = 0L; success_ = false; nextIndex_ = 0L; followerName_ = ""; missingFromQuorum_ = false; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private AppendEntriesReply( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { term_ = input.readUInt64(); break; } case 16: { success_ = input.readBool(); break; } case 24: { nextIndex_ = input.readUInt64(); break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); followerName_ = s; break; } case 40: { missingFromQuorum_ = input.readBool(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AppendEntriesReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AppendEntriesReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.class, ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.Builder.class); } public static final int TERM_FIELD_NUMBER = 1; private long term_; /** * <pre> ** currentTerm, for the leader to update itself * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } public static final int SUCCESS_FIELD_NUMBER = 2; private boolean success_; /** * <pre> ** true if the follower contained an entry matching prevLogIndex and prevLogTerm * </pre> * * <code>bool success = 2;</code> */ public boolean getSuccess() { return success_; } public static final int NEXTINDEX_FIELD_NUMBER = 3; private long nextIndex_; /** * <pre> ** * The last index replicated on this server. Serves to both signal replication, and * ask for logs starting at a given index. * </pre> * * <code>uint64 nextIndex = 3;</code> */ public long getNextIndex() { return nextIndex_; } public static final int FOLLOWERNAME_FIELD_NUMBER = 4; private volatile java.lang.Object followerName_; /** * <pre> ** The name of the follower that sent this reply. * </pre> * * <code>string followerName = 4;</code> */ public java.lang.String getFollowerName() { java.lang.Object ref = followerName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); followerName_ = s; return s; } } /** * <pre> ** The name of the follower that sent this reply. * </pre> * * <code>string followerName = 4;</code> */ public com.google.protobuf.ByteString getFollowerNameBytes() { java.lang.Object ref = followerName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); followerName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MISSINGFROMQUORUM_FIELD_NUMBER = 5; private boolean missingFromQuorum_; /** * <pre> ** NOT STANDARD RAFT: If true, this node is not in the quorum, and should perhaps be. * </pre> * * <code>bool missingFromQuorum = 5;</code> */ public boolean getMissingFromQuorum() { return missingFromQuorum_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (term_ != 0L) { output.writeUInt64(1, term_); } if (success_ != false) { output.writeBool(2, success_); } if (nextIndex_ != 0L) { output.writeUInt64(3, nextIndex_); } if (!getFollowerNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, followerName_); } if (missingFromQuorum_ != false) { output.writeBool(5, missingFromQuorum_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (term_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, term_); } if (success_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(2, success_); } if (nextIndex_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(3, nextIndex_); } if (!getFollowerNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, followerName_); } if (missingFromQuorum_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(5, missingFromQuorum_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply other = (ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) obj; boolean result = true; result = result && (getTerm() == other.getTerm()); result = result && (getSuccess() == other.getSuccess()); result = result && (getNextIndex() == other.getNextIndex()); result = result && getFollowerName() .equals(other.getFollowerName()); result = result && (getMissingFromQuorum() == other.getMissingFromQuorum()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTerm()); hash = (37 * hash) + SUCCESS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getSuccess()); hash = (37 * hash) + NEXTINDEX_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getNextIndex()); hash = (37 * hash) + FOLLOWERNAME_FIELD_NUMBER; hash = (53 * hash) + getFollowerName().hashCode(); hash = (37 * hash) + MISSINGFROMQUORUM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getMissingFromQuorum()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.AppendEntriesReply} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.AppendEntriesReply) ai.eloquent.raft.EloquentRaftProto.AppendEntriesReplyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AppendEntriesReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AppendEntriesReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.class, ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); term_ = 0L; success_ = false; nextIndex_ = 0L; followerName_ = ""; missingFromQuorum_ = false; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AppendEntriesReply_descriptor; } public ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply build() { ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply buildPartial() { ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply result = new ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply(this); result.term_ = term_; result.success_ = success_; result.nextIndex_ = nextIndex_; result.followerName_ = followerName_; result.missingFromQuorum_ = missingFromQuorum_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply other) { if (other == ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply.getDefaultInstance()) return this; if (other.getTerm() != 0L) { setTerm(other.getTerm()); } if (other.getSuccess() != false) { setSuccess(other.getSuccess()); } if (other.getNextIndex() != 0L) { setNextIndex(other.getNextIndex()); } if (!other.getFollowerName().isEmpty()) { followerName_ = other.followerName_; onChanged(); } if (other.getMissingFromQuorum() != false) { setMissingFromQuorum(other.getMissingFromQuorum()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private long term_ ; /** * <pre> ** currentTerm, for the leader to update itself * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } /** * <pre> ** currentTerm, for the leader to update itself * </pre> * * <code>uint64 term = 1;</code> */ public Builder setTerm(long value) { term_ = value; onChanged(); return this; } /** * <pre> ** currentTerm, for the leader to update itself * </pre> * * <code>uint64 term = 1;</code> */ public Builder clearTerm() { term_ = 0L; onChanged(); return this; } private boolean success_ ; /** * <pre> ** true if the follower contained an entry matching prevLogIndex and prevLogTerm * </pre> * * <code>bool success = 2;</code> */ public boolean getSuccess() { return success_; } /** * <pre> ** true if the follower contained an entry matching prevLogIndex and prevLogTerm * </pre> * * <code>bool success = 2;</code> */ public Builder setSuccess(boolean value) { success_ = value; onChanged(); return this; } /** * <pre> ** true if the follower contained an entry matching prevLogIndex and prevLogTerm * </pre> * * <code>bool success = 2;</code> */ public Builder clearSuccess() { success_ = false; onChanged(); return this; } private long nextIndex_ ; /** * <pre> ** * The last index replicated on this server. Serves to both signal replication, and * ask for logs starting at a given index. * </pre> * * <code>uint64 nextIndex = 3;</code> */ public long getNextIndex() { return nextIndex_; } /** * <pre> ** * The last index replicated on this server. Serves to both signal replication, and * ask for logs starting at a given index. * </pre> * * <code>uint64 nextIndex = 3;</code> */ public Builder setNextIndex(long value) { nextIndex_ = value; onChanged(); return this; } /** * <pre> ** * The last index replicated on this server. Serves to both signal replication, and * ask for logs starting at a given index. * </pre> * * <code>uint64 nextIndex = 3;</code> */ public Builder clearNextIndex() { nextIndex_ = 0L; onChanged(); return this; } private java.lang.Object followerName_ = ""; /** * <pre> ** The name of the follower that sent this reply. * </pre> * * <code>string followerName = 4;</code> */ public java.lang.String getFollowerName() { java.lang.Object ref = followerName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); followerName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** The name of the follower that sent this reply. * </pre> * * <code>string followerName = 4;</code> */ public com.google.protobuf.ByteString getFollowerNameBytes() { java.lang.Object ref = followerName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); followerName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** The name of the follower that sent this reply. * </pre> * * <code>string followerName = 4;</code> */ public Builder setFollowerName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } followerName_ = value; onChanged(); return this; } /** * <pre> ** The name of the follower that sent this reply. * </pre> * * <code>string followerName = 4;</code> */ public Builder clearFollowerName() { followerName_ = getDefaultInstance().getFollowerName(); onChanged(); return this; } /** * <pre> ** The name of the follower that sent this reply. * </pre> * * <code>string followerName = 4;</code> */ public Builder setFollowerNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); followerName_ = value; onChanged(); return this; } private boolean missingFromQuorum_ ; /** * <pre> ** NOT STANDARD RAFT: If true, this node is not in the quorum, and should perhaps be. * </pre> * * <code>bool missingFromQuorum = 5;</code> */ public boolean getMissingFromQuorum() { return missingFromQuorum_; } /** * <pre> ** NOT STANDARD RAFT: If true, this node is not in the quorum, and should perhaps be. * </pre> * * <code>bool missingFromQuorum = 5;</code> */ public Builder setMissingFromQuorum(boolean value) { missingFromQuorum_ = value; onChanged(); return this; } /** * <pre> ** NOT STANDARD RAFT: If true, this node is not in the quorum, and should perhaps be. * </pre> * * <code>bool missingFromQuorum = 5;</code> */ public Builder clearMissingFromQuorum() { missingFromQuorum_ = false; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.AppendEntriesReply) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.AppendEntriesReply) private static final ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply(); } public static ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AppendEntriesReply> PARSER = new com.google.protobuf.AbstractParser<AppendEntriesReply>() { public AppendEntriesReply parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new AppendEntriesReply(input, extensionRegistry); } }; public static com.google.protobuf.Parser<AppendEntriesReply> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AppendEntriesReply> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.AppendEntriesReply getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface RequestVoteRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.RequestVoteRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * Candidate's term * </pre> * * <code>uint64 term = 1;</code> */ long getTerm(); /** * <pre> * the candidate requesting votes * </pre> * * <code>string candidateName = 2;</code> */ java.lang.String getCandidateName(); /** * <pre> * the candidate requesting votes * </pre> * * <code>string candidateName = 2;</code> */ com.google.protobuf.ByteString getCandidateNameBytes(); /** * <pre> * index of candidate's last log entry * </pre> * * <code>uint64 lastLogIndex = 3;</code> */ long getLastLogIndex(); /** * <pre> * term of candidate's last log entry * </pre> * * <code>uint64 lastLogTerm = 4;</code> */ long getLastLogTerm(); } /** * Protobuf type {@code ai.eloquent.raft.RequestVoteRequest} */ public static final class RequestVoteRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.RequestVoteRequest) RequestVoteRequestOrBuilder { private static final long serialVersionUID = 0L; // Use RequestVoteRequest.newBuilder() to construct. private RequestVoteRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RequestVoteRequest() { term_ = 0L; candidateName_ = ""; lastLogIndex_ = 0L; lastLogTerm_ = 0L; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private RequestVoteRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { term_ = input.readUInt64(); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); candidateName_ = s; break; } case 24: { lastLogIndex_ = input.readUInt64(); break; } case 32: { lastLogTerm_ = input.readUInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RequestVoteRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RequestVoteRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.class, ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.Builder.class); } public static final int TERM_FIELD_NUMBER = 1; private long term_; /** * <pre> * Candidate's term * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } public static final int CANDIDATENAME_FIELD_NUMBER = 2; private volatile java.lang.Object candidateName_; /** * <pre> * the candidate requesting votes * </pre> * * <code>string candidateName = 2;</code> */ public java.lang.String getCandidateName() { java.lang.Object ref = candidateName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); candidateName_ = s; return s; } } /** * <pre> * the candidate requesting votes * </pre> * * <code>string candidateName = 2;</code> */ public com.google.protobuf.ByteString getCandidateNameBytes() { java.lang.Object ref = candidateName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); candidateName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LASTLOGINDEX_FIELD_NUMBER = 3; private long lastLogIndex_; /** * <pre> * index of candidate's last log entry * </pre> * * <code>uint64 lastLogIndex = 3;</code> */ public long getLastLogIndex() { return lastLogIndex_; } public static final int LASTLOGTERM_FIELD_NUMBER = 4; private long lastLogTerm_; /** * <pre> * term of candidate's last log entry * </pre> * * <code>uint64 lastLogTerm = 4;</code> */ public long getLastLogTerm() { return lastLogTerm_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (term_ != 0L) { output.writeUInt64(1, term_); } if (!getCandidateNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, candidateName_); } if (lastLogIndex_ != 0L) { output.writeUInt64(3, lastLogIndex_); } if (lastLogTerm_ != 0L) { output.writeUInt64(4, lastLogTerm_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (term_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, term_); } if (!getCandidateNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, candidateName_); } if (lastLogIndex_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(3, lastLogIndex_); } if (lastLogTerm_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, lastLogTerm_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest other = (ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) obj; boolean result = true; result = result && (getTerm() == other.getTerm()); result = result && getCandidateName() .equals(other.getCandidateName()); result = result && (getLastLogIndex() == other.getLastLogIndex()); result = result && (getLastLogTerm() == other.getLastLogTerm()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTerm()); hash = (37 * hash) + CANDIDATENAME_FIELD_NUMBER; hash = (53 * hash) + getCandidateName().hashCode(); hash = (37 * hash) + LASTLOGINDEX_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLastLogIndex()); hash = (37 * hash) + LASTLOGTERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLastLogTerm()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.RequestVoteRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.RequestVoteRequest) ai.eloquent.raft.EloquentRaftProto.RequestVoteRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RequestVoteRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RequestVoteRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.class, ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); term_ = 0L; candidateName_ = ""; lastLogIndex_ = 0L; lastLogTerm_ = 0L; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RequestVoteRequest_descriptor; } public ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest build() { ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest buildPartial() { ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest result = new ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest(this); result.term_ = term_; result.candidateName_ = candidateName_; result.lastLogIndex_ = lastLogIndex_; result.lastLogTerm_ = lastLogTerm_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest other) { if (other == ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest.getDefaultInstance()) return this; if (other.getTerm() != 0L) { setTerm(other.getTerm()); } if (!other.getCandidateName().isEmpty()) { candidateName_ = other.candidateName_; onChanged(); } if (other.getLastLogIndex() != 0L) { setLastLogIndex(other.getLastLogIndex()); } if (other.getLastLogTerm() != 0L) { setLastLogTerm(other.getLastLogTerm()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private long term_ ; /** * <pre> * Candidate's term * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } /** * <pre> * Candidate's term * </pre> * * <code>uint64 term = 1;</code> */ public Builder setTerm(long value) { term_ = value; onChanged(); return this; } /** * <pre> * Candidate's term * </pre> * * <code>uint64 term = 1;</code> */ public Builder clearTerm() { term_ = 0L; onChanged(); return this; } private java.lang.Object candidateName_ = ""; /** * <pre> * the candidate requesting votes * </pre> * * <code>string candidateName = 2;</code> */ public java.lang.String getCandidateName() { java.lang.Object ref = candidateName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); candidateName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * the candidate requesting votes * </pre> * * <code>string candidateName = 2;</code> */ public com.google.protobuf.ByteString getCandidateNameBytes() { java.lang.Object ref = candidateName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); candidateName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * the candidate requesting votes * </pre> * * <code>string candidateName = 2;</code> */ public Builder setCandidateName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } candidateName_ = value; onChanged(); return this; } /** * <pre> * the candidate requesting votes * </pre> * * <code>string candidateName = 2;</code> */ public Builder clearCandidateName() { candidateName_ = getDefaultInstance().getCandidateName(); onChanged(); return this; } /** * <pre> * the candidate requesting votes * </pre> * * <code>string candidateName = 2;</code> */ public Builder setCandidateNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); candidateName_ = value; onChanged(); return this; } private long lastLogIndex_ ; /** * <pre> * index of candidate's last log entry * </pre> * * <code>uint64 lastLogIndex = 3;</code> */ public long getLastLogIndex() { return lastLogIndex_; } /** * <pre> * index of candidate's last log entry * </pre> * * <code>uint64 lastLogIndex = 3;</code> */ public Builder setLastLogIndex(long value) { lastLogIndex_ = value; onChanged(); return this; } /** * <pre> * index of candidate's last log entry * </pre> * * <code>uint64 lastLogIndex = 3;</code> */ public Builder clearLastLogIndex() { lastLogIndex_ = 0L; onChanged(); return this; } private long lastLogTerm_ ; /** * <pre> * term of candidate's last log entry * </pre> * * <code>uint64 lastLogTerm = 4;</code> */ public long getLastLogTerm() { return lastLogTerm_; } /** * <pre> * term of candidate's last log entry * </pre> * * <code>uint64 lastLogTerm = 4;</code> */ public Builder setLastLogTerm(long value) { lastLogTerm_ = value; onChanged(); return this; } /** * <pre> * term of candidate's last log entry * </pre> * * <code>uint64 lastLogTerm = 4;</code> */ public Builder clearLastLogTerm() { lastLogTerm_ = 0L; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.RequestVoteRequest) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.RequestVoteRequest) private static final ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest(); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RequestVoteRequest> PARSER = new com.google.protobuf.AbstractParser<RequestVoteRequest>() { public RequestVoteRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new RequestVoteRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<RequestVoteRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RequestVoteRequest> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.RequestVoteRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface RequestVoteReplyOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.RequestVoteReply) com.google.protobuf.MessageOrBuilder { /** * <pre> * the term of the leader, echoed back to it. * </pre> * * <code>uint64 term = 1;</code> */ long getTerm(); /** * <pre> * the term of the follower, who is giving the vote. * </pre> * * <code>uint64 followerTerm = 4;</code> */ long getFollowerTerm(); /** * <pre> * true means candidate received vote * </pre> * * <code>bool voteGranted = 2;</code> */ boolean getVoteGranted(); /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ java.lang.String getFollowerName(); /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ com.google.protobuf.ByteString getFollowerNameBytes(); } /** * Protobuf type {@code ai.eloquent.raft.RequestVoteReply} */ public static final class RequestVoteReply extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.RequestVoteReply) RequestVoteReplyOrBuilder { private static final long serialVersionUID = 0L; // Use RequestVoteReply.newBuilder() to construct. private RequestVoteReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RequestVoteReply() { term_ = 0L; followerTerm_ = 0L; voteGranted_ = false; followerName_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private RequestVoteReply( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { term_ = input.readUInt64(); break; } case 16: { voteGranted_ = input.readBool(); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); followerName_ = s; break; } case 32: { followerTerm_ = input.readUInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RequestVoteReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RequestVoteReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.class, ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.Builder.class); } public static final int TERM_FIELD_NUMBER = 1; private long term_; /** * <pre> * the term of the leader, echoed back to it. * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } public static final int FOLLOWERTERM_FIELD_NUMBER = 4; private long followerTerm_; /** * <pre> * the term of the follower, who is giving the vote. * </pre> * * <code>uint64 followerTerm = 4;</code> */ public long getFollowerTerm() { return followerTerm_; } public static final int VOTEGRANTED_FIELD_NUMBER = 2; private boolean voteGranted_; /** * <pre> * true means candidate received vote * </pre> * * <code>bool voteGranted = 2;</code> */ public boolean getVoteGranted() { return voteGranted_; } public static final int FOLLOWERNAME_FIELD_NUMBER = 3; private volatile java.lang.Object followerName_; /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public java.lang.String getFollowerName() { java.lang.Object ref = followerName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); followerName_ = s; return s; } } /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public com.google.protobuf.ByteString getFollowerNameBytes() { java.lang.Object ref = followerName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); followerName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (term_ != 0L) { output.writeUInt64(1, term_); } if (voteGranted_ != false) { output.writeBool(2, voteGranted_); } if (!getFollowerNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, followerName_); } if (followerTerm_ != 0L) { output.writeUInt64(4, followerTerm_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (term_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, term_); } if (voteGranted_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(2, voteGranted_); } if (!getFollowerNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, followerName_); } if (followerTerm_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, followerTerm_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.RequestVoteReply)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.RequestVoteReply other = (ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) obj; boolean result = true; result = result && (getTerm() == other.getTerm()); result = result && (getFollowerTerm() == other.getFollowerTerm()); result = result && (getVoteGranted() == other.getVoteGranted()); result = result && getFollowerName() .equals(other.getFollowerName()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTerm()); hash = (37 * hash) + FOLLOWERTERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getFollowerTerm()); hash = (37 * hash) + VOTEGRANTED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getVoteGranted()); hash = (37 * hash) + FOLLOWERNAME_FIELD_NUMBER; hash = (53 * hash) + getFollowerName().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.RequestVoteReply prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.RequestVoteReply} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.RequestVoteReply) ai.eloquent.raft.EloquentRaftProto.RequestVoteReplyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RequestVoteReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RequestVoteReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.class, ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); term_ = 0L; followerTerm_ = 0L; voteGranted_ = false; followerName_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RequestVoteReply_descriptor; } public ai.eloquent.raft.EloquentRaftProto.RequestVoteReply getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.RequestVoteReply build() { ai.eloquent.raft.EloquentRaftProto.RequestVoteReply result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.RequestVoteReply buildPartial() { ai.eloquent.raft.EloquentRaftProto.RequestVoteReply result = new ai.eloquent.raft.EloquentRaftProto.RequestVoteReply(this); result.term_ = term_; result.followerTerm_ = followerTerm_; result.voteGranted_ = voteGranted_; result.followerName_ = followerName_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.RequestVoteReply)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.RequestVoteReply other) { if (other == ai.eloquent.raft.EloquentRaftProto.RequestVoteReply.getDefaultInstance()) return this; if (other.getTerm() != 0L) { setTerm(other.getTerm()); } if (other.getFollowerTerm() != 0L) { setFollowerTerm(other.getFollowerTerm()); } if (other.getVoteGranted() != false) { setVoteGranted(other.getVoteGranted()); } if (!other.getFollowerName().isEmpty()) { followerName_ = other.followerName_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.RequestVoteReply parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.RequestVoteReply) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private long term_ ; /** * <pre> * the term of the leader, echoed back to it. * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } /** * <pre> * the term of the leader, echoed back to it. * </pre> * * <code>uint64 term = 1;</code> */ public Builder setTerm(long value) { term_ = value; onChanged(); return this; } /** * <pre> * the term of the leader, echoed back to it. * </pre> * * <code>uint64 term = 1;</code> */ public Builder clearTerm() { term_ = 0L; onChanged(); return this; } private long followerTerm_ ; /** * <pre> * the term of the follower, who is giving the vote. * </pre> * * <code>uint64 followerTerm = 4;</code> */ public long getFollowerTerm() { return followerTerm_; } /** * <pre> * the term of the follower, who is giving the vote. * </pre> * * <code>uint64 followerTerm = 4;</code> */ public Builder setFollowerTerm(long value) { followerTerm_ = value; onChanged(); return this; } /** * <pre> * the term of the follower, who is giving the vote. * </pre> * * <code>uint64 followerTerm = 4;</code> */ public Builder clearFollowerTerm() { followerTerm_ = 0L; onChanged(); return this; } private boolean voteGranted_ ; /** * <pre> * true means candidate received vote * </pre> * * <code>bool voteGranted = 2;</code> */ public boolean getVoteGranted() { return voteGranted_; } /** * <pre> * true means candidate received vote * </pre> * * <code>bool voteGranted = 2;</code> */ public Builder setVoteGranted(boolean value) { voteGranted_ = value; onChanged(); return this; } /** * <pre> * true means candidate received vote * </pre> * * <code>bool voteGranted = 2;</code> */ public Builder clearVoteGranted() { voteGranted_ = false; onChanged(); return this; } private java.lang.Object followerName_ = ""; /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public java.lang.String getFollowerName() { java.lang.Object ref = followerName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); followerName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public com.google.protobuf.ByteString getFollowerNameBytes() { java.lang.Object ref = followerName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); followerName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public Builder setFollowerName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } followerName_ = value; onChanged(); return this; } /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public Builder clearFollowerName() { followerName_ = getDefaultInstance().getFollowerName(); onChanged(); return this; } /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public Builder setFollowerNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); followerName_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.RequestVoteReply) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.RequestVoteReply) private static final ai.eloquent.raft.EloquentRaftProto.RequestVoteReply DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.RequestVoteReply(); } public static ai.eloquent.raft.EloquentRaftProto.RequestVoteReply getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RequestVoteReply> PARSER = new com.google.protobuf.AbstractParser<RequestVoteReply>() { public RequestVoteReply parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new RequestVoteReply(input, extensionRegistry); } }; public static com.google.protobuf.Parser<RequestVoteReply> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RequestVoteReply> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.RequestVoteReply getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ApplyTransitionRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.ApplyTransitionRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * term of the requesting node * </pre> * * <code>uint64 term = 1;</code> */ long getTerm(); /** * <pre> * serialized copy of the state transition * </pre> * * <code>bytes transition = 2;</code> */ com.google.protobuf.ByteString getTransition(); /** * <pre> * or, the addition of a hospice member * </pre> * * <code>string new_hospice_member = 4;</code> */ java.lang.String getNewHospiceMember(); /** * <pre> * or, the addition of a hospice member * </pre> * * <code>string new_hospice_member = 4;</code> */ com.google.protobuf.ByteString getNewHospiceMemberBytes(); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ java.util.List<java.lang.String> getForwardedByList(); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ int getForwardedByCount(); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ java.lang.String getForwardedBy(int index); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ com.google.protobuf.ByteString getForwardedByBytes(int index); public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.PayloadCase getPayloadCase(); } /** * Protobuf type {@code ai.eloquent.raft.ApplyTransitionRequest} */ public static final class ApplyTransitionRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.ApplyTransitionRequest) ApplyTransitionRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ApplyTransitionRequest.newBuilder() to construct. private ApplyTransitionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ApplyTransitionRequest() { term_ = 0L; forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ApplyTransitionRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { term_ = input.readUInt64(); break; } case 18: { payloadCase_ = 2; payload_ = input.readBytes(); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { forwardedBy_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000008; } forwardedBy_.add(s); break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); payloadCase_ = 4; payload_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { forwardedBy_ = forwardedBy_.getUnmodifiableView(); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_ApplyTransitionRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_ApplyTransitionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.class, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.Builder.class); } private int bitField0_; private int payloadCase_ = 0; private java.lang.Object payload_; public enum PayloadCase implements com.google.protobuf.Internal.EnumLite { TRANSITION(2), NEW_HOSPICE_MEMBER(4), PAYLOAD_NOT_SET(0); private final int value; private PayloadCase(int value) { this.value = value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static PayloadCase valueOf(int value) { return forNumber(value); } public static PayloadCase forNumber(int value) { switch (value) { case 2: return TRANSITION; case 4: return NEW_HOSPICE_MEMBER; case 0: return PAYLOAD_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public PayloadCase getPayloadCase() { return PayloadCase.forNumber( payloadCase_); } public static final int TERM_FIELD_NUMBER = 1; private long term_; /** * <pre> * term of the requesting node * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } public static final int TRANSITION_FIELD_NUMBER = 2; /** * <pre> * serialized copy of the state transition * </pre> * * <code>bytes transition = 2;</code> */ public com.google.protobuf.ByteString getTransition() { if (payloadCase_ == 2) { return (com.google.protobuf.ByteString) payload_; } return com.google.protobuf.ByteString.EMPTY; } public static final int NEW_HOSPICE_MEMBER_FIELD_NUMBER = 4; /** * <pre> * or, the addition of a hospice member * </pre> * * <code>string new_hospice_member = 4;</code> */ public java.lang.String getNewHospiceMember() { java.lang.Object ref = ""; if (payloadCase_ == 4) { ref = payload_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (payloadCase_ == 4) { payload_ = s; } return s; } } /** * <pre> * or, the addition of a hospice member * </pre> * * <code>string new_hospice_member = 4;</code> */ public com.google.protobuf.ByteString getNewHospiceMemberBytes() { java.lang.Object ref = ""; if (payloadCase_ == 4) { ref = payload_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (payloadCase_ == 4) { payload_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FORWARDEDBY_FIELD_NUMBER = 3; private com.google.protobuf.LazyStringList forwardedBy_; /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ProtocolStringList getForwardedByList() { return forwardedBy_; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public int getForwardedByCount() { return forwardedBy_.size(); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public java.lang.String getForwardedBy(int index) { return forwardedBy_.get(index); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ByteString getForwardedByBytes(int index) { return forwardedBy_.getByteString(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (term_ != 0L) { output.writeUInt64(1, term_); } if (payloadCase_ == 2) { output.writeBytes( 2, (com.google.protobuf.ByteString) payload_); } for (int i = 0; i < forwardedBy_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, forwardedBy_.getRaw(i)); } if (payloadCase_ == 4) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, payload_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (term_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, term_); } if (payloadCase_ == 2) { size += com.google.protobuf.CodedOutputStream .computeBytesSize( 2, (com.google.protobuf.ByteString) payload_); } { int dataSize = 0; for (int i = 0; i < forwardedBy_.size(); i++) { dataSize += computeStringSizeNoTag(forwardedBy_.getRaw(i)); } size += dataSize; size += 1 * getForwardedByList().size(); } if (payloadCase_ == 4) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, payload_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest other = (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) obj; boolean result = true; result = result && (getTerm() == other.getTerm()); result = result && getForwardedByList() .equals(other.getForwardedByList()); result = result && getPayloadCase().equals( other.getPayloadCase()); if (!result) return false; switch (payloadCase_) { case 2: result = result && getTransition() .equals(other.getTransition()); break; case 4: result = result && getNewHospiceMember() .equals(other.getNewHospiceMember()); break; case 0: default: } result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTerm()); if (getForwardedByCount() > 0) { hash = (37 * hash) + FORWARDEDBY_FIELD_NUMBER; hash = (53 * hash) + getForwardedByList().hashCode(); } switch (payloadCase_) { case 2: hash = (37 * hash) + TRANSITION_FIELD_NUMBER; hash = (53 * hash) + getTransition().hashCode(); break; case 4: hash = (37 * hash) + NEW_HOSPICE_MEMBER_FIELD_NUMBER; hash = (53 * hash) + getNewHospiceMember().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.ApplyTransitionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.ApplyTransitionRequest) ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_ApplyTransitionRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_ApplyTransitionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.class, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); term_ = 0L; forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); payloadCase_ = 0; payload_ = null; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_ApplyTransitionRequest_descriptor; } public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest build() { ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest buildPartial() { ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest result = new ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.term_ = term_; if (payloadCase_ == 2) { result.payload_ = payload_; } if (payloadCase_ == 4) { result.payload_ = payload_; } if (((bitField0_ & 0x00000008) == 0x00000008)) { forwardedBy_ = forwardedBy_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000008); } result.forwardedBy_ = forwardedBy_; result.bitField0_ = to_bitField0_; result.payloadCase_ = payloadCase_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest other) { if (other == ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest.getDefaultInstance()) return this; if (other.getTerm() != 0L) { setTerm(other.getTerm()); } if (!other.forwardedBy_.isEmpty()) { if (forwardedBy_.isEmpty()) { forwardedBy_ = other.forwardedBy_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensureForwardedByIsMutable(); forwardedBy_.addAll(other.forwardedBy_); } onChanged(); } switch (other.getPayloadCase()) { case TRANSITION: { setTransition(other.getTransition()); break; } case NEW_HOSPICE_MEMBER: { payloadCase_ = 4; payload_ = other.payload_; onChanged(); break; } case PAYLOAD_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int payloadCase_ = 0; private java.lang.Object payload_; public PayloadCase getPayloadCase() { return PayloadCase.forNumber( payloadCase_); } public Builder clearPayload() { payloadCase_ = 0; payload_ = null; onChanged(); return this; } private int bitField0_; private long term_ ; /** * <pre> * term of the requesting node * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } /** * <pre> * term of the requesting node * </pre> * * <code>uint64 term = 1;</code> */ public Builder setTerm(long value) { term_ = value; onChanged(); return this; } /** * <pre> * term of the requesting node * </pre> * * <code>uint64 term = 1;</code> */ public Builder clearTerm() { term_ = 0L; onChanged(); return this; } /** * <pre> * serialized copy of the state transition * </pre> * * <code>bytes transition = 2;</code> */ public com.google.protobuf.ByteString getTransition() { if (payloadCase_ == 2) { return (com.google.protobuf.ByteString) payload_; } return com.google.protobuf.ByteString.EMPTY; } /** * <pre> * serialized copy of the state transition * </pre> * * <code>bytes transition = 2;</code> */ public Builder setTransition(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } payloadCase_ = 2; payload_ = value; onChanged(); return this; } /** * <pre> * serialized copy of the state transition * </pre> * * <code>bytes transition = 2;</code> */ public Builder clearTransition() { if (payloadCase_ == 2) { payloadCase_ = 0; payload_ = null; onChanged(); } return this; } /** * <pre> * or, the addition of a hospice member * </pre> * * <code>string new_hospice_member = 4;</code> */ public java.lang.String getNewHospiceMember() { java.lang.Object ref = ""; if (payloadCase_ == 4) { ref = payload_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (payloadCase_ == 4) { payload_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <pre> * or, the addition of a hospice member * </pre> * * <code>string new_hospice_member = 4;</code> */ public com.google.protobuf.ByteString getNewHospiceMemberBytes() { java.lang.Object ref = ""; if (payloadCase_ == 4) { ref = payload_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (payloadCase_ == 4) { payload_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * or, the addition of a hospice member * </pre> * * <code>string new_hospice_member = 4;</code> */ public Builder setNewHospiceMember( java.lang.String value) { if (value == null) { throw new NullPointerException(); } payloadCase_ = 4; payload_ = value; onChanged(); return this; } /** * <pre> * or, the addition of a hospice member * </pre> * * <code>string new_hospice_member = 4;</code> */ public Builder clearNewHospiceMember() { if (payloadCase_ == 4) { payloadCase_ = 0; payload_ = null; onChanged(); } return this; } /** * <pre> * or, the addition of a hospice member * </pre> * * <code>string new_hospice_member = 4;</code> */ public Builder setNewHospiceMemberBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); payloadCase_ = 4; payload_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureForwardedByIsMutable() { if (!((bitField0_ & 0x00000008) == 0x00000008)) { forwardedBy_ = new com.google.protobuf.LazyStringArrayList(forwardedBy_); bitField0_ |= 0x00000008; } } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ProtocolStringList getForwardedByList() { return forwardedBy_.getUnmodifiableView(); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public int getForwardedByCount() { return forwardedBy_.size(); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public java.lang.String getForwardedBy(int index) { return forwardedBy_.get(index); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ByteString getForwardedByBytes(int index) { return forwardedBy_.getByteString(index); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder setForwardedBy( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureForwardedByIsMutable(); forwardedBy_.set(index, value); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder addForwardedBy( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureForwardedByIsMutable(); forwardedBy_.add(value); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder addAllForwardedBy( java.lang.Iterable<java.lang.String> values) { ensureForwardedByIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, forwardedBy_); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder clearForwardedBy() { forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder addForwardedByBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureForwardedByIsMutable(); forwardedBy_.add(value); onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.ApplyTransitionRequest) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.ApplyTransitionRequest) private static final ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest(); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ApplyTransitionRequest> PARSER = new com.google.protobuf.AbstractParser<ApplyTransitionRequest>() { public ApplyTransitionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ApplyTransitionRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ApplyTransitionRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ApplyTransitionRequest> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ApplyTransitionReplyOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.ApplyTransitionReply) com.google.protobuf.MessageOrBuilder { /** * <pre> * currentTerm, for requester to update itself * </pre> * * <code>uint64 term = 1;</code> */ long getTerm(); /** * <pre> * false if we this node is no longer the leader and the transition couldn't be applied * </pre> * * <code>bool success = 2;</code> */ boolean getSuccess(); /** * <pre> * the index of the log entry * </pre> * * <code>uint64 newEntryIndex = 3;</code> */ long getNewEntryIndex(); /** * <pre> * the term of the log entry * </pre> * * <code>uint64 newEntryTerm = 4;</code> */ long getNewEntryTerm(); } /** * Protobuf type {@code ai.eloquent.raft.ApplyTransitionReply} */ public static final class ApplyTransitionReply extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.ApplyTransitionReply) ApplyTransitionReplyOrBuilder { private static final long serialVersionUID = 0L; // Use ApplyTransitionReply.newBuilder() to construct. private ApplyTransitionReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ApplyTransitionReply() { term_ = 0L; success_ = false; newEntryIndex_ = 0L; newEntryTerm_ = 0L; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ApplyTransitionReply( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { term_ = input.readUInt64(); break; } case 16: { success_ = input.readBool(); break; } case 24: { newEntryIndex_ = input.readUInt64(); break; } case 32: { newEntryTerm_ = input.readUInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_ApplyTransitionReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_ApplyTransitionReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.class, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.Builder.class); } public static final int TERM_FIELD_NUMBER = 1; private long term_; /** * <pre> * currentTerm, for requester to update itself * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } public static final int SUCCESS_FIELD_NUMBER = 2; private boolean success_; /** * <pre> * false if we this node is no longer the leader and the transition couldn't be applied * </pre> * * <code>bool success = 2;</code> */ public boolean getSuccess() { return success_; } public static final int NEWENTRYINDEX_FIELD_NUMBER = 3; private long newEntryIndex_; /** * <pre> * the index of the log entry * </pre> * * <code>uint64 newEntryIndex = 3;</code> */ public long getNewEntryIndex() { return newEntryIndex_; } public static final int NEWENTRYTERM_FIELD_NUMBER = 4; private long newEntryTerm_; /** * <pre> * the term of the log entry * </pre> * * <code>uint64 newEntryTerm = 4;</code> */ public long getNewEntryTerm() { return newEntryTerm_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (term_ != 0L) { output.writeUInt64(1, term_); } if (success_ != false) { output.writeBool(2, success_); } if (newEntryIndex_ != 0L) { output.writeUInt64(3, newEntryIndex_); } if (newEntryTerm_ != 0L) { output.writeUInt64(4, newEntryTerm_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (term_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, term_); } if (success_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(2, success_); } if (newEntryIndex_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(3, newEntryIndex_); } if (newEntryTerm_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, newEntryTerm_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply other = (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) obj; boolean result = true; result = result && (getTerm() == other.getTerm()); result = result && (getSuccess() == other.getSuccess()); result = result && (getNewEntryIndex() == other.getNewEntryIndex()); result = result && (getNewEntryTerm() == other.getNewEntryTerm()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTerm()); hash = (37 * hash) + SUCCESS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getSuccess()); hash = (37 * hash) + NEWENTRYINDEX_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getNewEntryIndex()); hash = (37 * hash) + NEWENTRYTERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getNewEntryTerm()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.ApplyTransitionReply} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.ApplyTransitionReply) ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReplyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_ApplyTransitionReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_ApplyTransitionReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.class, ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); term_ = 0L; success_ = false; newEntryIndex_ = 0L; newEntryTerm_ = 0L; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_ApplyTransitionReply_descriptor; } public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply build() { ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply buildPartial() { ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply result = new ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply(this); result.term_ = term_; result.success_ = success_; result.newEntryIndex_ = newEntryIndex_; result.newEntryTerm_ = newEntryTerm_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply other) { if (other == ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply.getDefaultInstance()) return this; if (other.getTerm() != 0L) { setTerm(other.getTerm()); } if (other.getSuccess() != false) { setSuccess(other.getSuccess()); } if (other.getNewEntryIndex() != 0L) { setNewEntryIndex(other.getNewEntryIndex()); } if (other.getNewEntryTerm() != 0L) { setNewEntryTerm(other.getNewEntryTerm()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private long term_ ; /** * <pre> * currentTerm, for requester to update itself * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } /** * <pre> * currentTerm, for requester to update itself * </pre> * * <code>uint64 term = 1;</code> */ public Builder setTerm(long value) { term_ = value; onChanged(); return this; } /** * <pre> * currentTerm, for requester to update itself * </pre> * * <code>uint64 term = 1;</code> */ public Builder clearTerm() { term_ = 0L; onChanged(); return this; } private boolean success_ ; /** * <pre> * false if we this node is no longer the leader and the transition couldn't be applied * </pre> * * <code>bool success = 2;</code> */ public boolean getSuccess() { return success_; } /** * <pre> * false if we this node is no longer the leader and the transition couldn't be applied * </pre> * * <code>bool success = 2;</code> */ public Builder setSuccess(boolean value) { success_ = value; onChanged(); return this; } /** * <pre> * false if we this node is no longer the leader and the transition couldn't be applied * </pre> * * <code>bool success = 2;</code> */ public Builder clearSuccess() { success_ = false; onChanged(); return this; } private long newEntryIndex_ ; /** * <pre> * the index of the log entry * </pre> * * <code>uint64 newEntryIndex = 3;</code> */ public long getNewEntryIndex() { return newEntryIndex_; } /** * <pre> * the index of the log entry * </pre> * * <code>uint64 newEntryIndex = 3;</code> */ public Builder setNewEntryIndex(long value) { newEntryIndex_ = value; onChanged(); return this; } /** * <pre> * the index of the log entry * </pre> * * <code>uint64 newEntryIndex = 3;</code> */ public Builder clearNewEntryIndex() { newEntryIndex_ = 0L; onChanged(); return this; } private long newEntryTerm_ ; /** * <pre> * the term of the log entry * </pre> * * <code>uint64 newEntryTerm = 4;</code> */ public long getNewEntryTerm() { return newEntryTerm_; } /** * <pre> * the term of the log entry * </pre> * * <code>uint64 newEntryTerm = 4;</code> */ public Builder setNewEntryTerm(long value) { newEntryTerm_ = value; onChanged(); return this; } /** * <pre> * the term of the log entry * </pre> * * <code>uint64 newEntryTerm = 4;</code> */ public Builder clearNewEntryTerm() { newEntryTerm_ = 0L; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.ApplyTransitionReply) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.ApplyTransitionReply) private static final ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply(); } public static ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ApplyTransitionReply> PARSER = new com.google.protobuf.AbstractParser<ApplyTransitionReply>() { public ApplyTransitionReply parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ApplyTransitionReply(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ApplyTransitionReply> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ApplyTransitionReply> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.ApplyTransitionReply getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface LogEntryOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.LogEntry) com.google.protobuf.MessageOrBuilder { /** * <pre> * the index of the log entry * </pre> * * <code>uint64 index = 1;</code> */ long getIndex(); /** * <pre> * term when the log entry was created * </pre> * * <code>uint64 term = 2;</code> */ long getTerm(); /** * <pre> * the type of the log entry * </pre> * * <code>.ai.eloquent.raft.LogEntryType type = 3;</code> */ int getTypeValue(); /** * <pre> * the type of the log entry * </pre> * * <code>.ai.eloquent.raft.LogEntryType type = 3;</code> */ ai.eloquent.raft.EloquentRaftProto.LogEntryType getType(); /** * <pre> * the raw bytes of the transition request - only in TRANSITION messages * </pre> * * <code>bytes transition = 4;</code> */ com.google.protobuf.ByteString getTransition(); /** * <pre> * or, the addition of a hospice member - only in TRANSITION messages * </pre> * * <code>string new_hospice_member = 6;</code> */ java.lang.String getNewHospiceMember(); /** * <pre> * or, the addition of a hospice member - only in TRANSITION messages * </pre> * * <code>string new_hospice_member = 6;</code> */ com.google.protobuf.ByteString getNewHospiceMemberBytes(); /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ java.util.List<java.lang.String> getConfigurationList(); /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ int getConfigurationCount(); /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ java.lang.String getConfiguration(int index); /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ com.google.protobuf.ByteString getConfigurationBytes(int index); public ai.eloquent.raft.EloquentRaftProto.LogEntry.PayloadCase getPayloadCase(); } /** * Protobuf type {@code ai.eloquent.raft.LogEntry} */ public static final class LogEntry extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.LogEntry) LogEntryOrBuilder { private static final long serialVersionUID = 0L; // Use LogEntry.newBuilder() to construct. private LogEntry(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private LogEntry() { index_ = 0L; term_ = 0L; type_ = 0; configuration_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private LogEntry( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { index_ = input.readUInt64(); break; } case 16: { term_ = input.readUInt64(); break; } case 24: { int rawValue = input.readEnum(); type_ = rawValue; break; } case 34: { payloadCase_ = 4; payload_ = input.readBytes(); break; } case 42: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) { configuration_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000020; } configuration_.add(s); break; } case 50: { java.lang.String s = input.readStringRequireUtf8(); payloadCase_ = 6; payload_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) { configuration_ = configuration_.getUnmodifiableView(); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LogEntry_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LogEntry_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.LogEntry.class, ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder.class); } private int bitField0_; private int payloadCase_ = 0; private java.lang.Object payload_; public enum PayloadCase implements com.google.protobuf.Internal.EnumLite { TRANSITION(4), NEW_HOSPICE_MEMBER(6), PAYLOAD_NOT_SET(0); private final int value; private PayloadCase(int value) { this.value = value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static PayloadCase valueOf(int value) { return forNumber(value); } public static PayloadCase forNumber(int value) { switch (value) { case 4: return TRANSITION; case 6: return NEW_HOSPICE_MEMBER; case 0: return PAYLOAD_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public PayloadCase getPayloadCase() { return PayloadCase.forNumber( payloadCase_); } public static final int INDEX_FIELD_NUMBER = 1; private long index_; /** * <pre> * the index of the log entry * </pre> * * <code>uint64 index = 1;</code> */ public long getIndex() { return index_; } public static final int TERM_FIELD_NUMBER = 2; private long term_; /** * <pre> * term when the log entry was created * </pre> * * <code>uint64 term = 2;</code> */ public long getTerm() { return term_; } public static final int TYPE_FIELD_NUMBER = 3; private int type_; /** * <pre> * the type of the log entry * </pre> * * <code>.ai.eloquent.raft.LogEntryType type = 3;</code> */ public int getTypeValue() { return type_; } /** * <pre> * the type of the log entry * </pre> * * <code>.ai.eloquent.raft.LogEntryType type = 3;</code> */ public ai.eloquent.raft.EloquentRaftProto.LogEntryType getType() { ai.eloquent.raft.EloquentRaftProto.LogEntryType result = ai.eloquent.raft.EloquentRaftProto.LogEntryType.valueOf(type_); return result == null ? ai.eloquent.raft.EloquentRaftProto.LogEntryType.UNRECOGNIZED : result; } public static final int TRANSITION_FIELD_NUMBER = 4; /** * <pre> * the raw bytes of the transition request - only in TRANSITION messages * </pre> * * <code>bytes transition = 4;</code> */ public com.google.protobuf.ByteString getTransition() { if (payloadCase_ == 4) { return (com.google.protobuf.ByteString) payload_; } return com.google.protobuf.ByteString.EMPTY; } public static final int NEW_HOSPICE_MEMBER_FIELD_NUMBER = 6; /** * <pre> * or, the addition of a hospice member - only in TRANSITION messages * </pre> * * <code>string new_hospice_member = 6;</code> */ public java.lang.String getNewHospiceMember() { java.lang.Object ref = ""; if (payloadCase_ == 6) { ref = payload_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (payloadCase_ == 6) { payload_ = s; } return s; } } /** * <pre> * or, the addition of a hospice member - only in TRANSITION messages * </pre> * * <code>string new_hospice_member = 6;</code> */ public com.google.protobuf.ByteString getNewHospiceMemberBytes() { java.lang.Object ref = ""; if (payloadCase_ == 6) { ref = payload_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (payloadCase_ == 6) { payload_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONFIGURATION_FIELD_NUMBER = 5; private com.google.protobuf.LazyStringList configuration_; /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public com.google.protobuf.ProtocolStringList getConfigurationList() { return configuration_; } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public int getConfigurationCount() { return configuration_.size(); } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public java.lang.String getConfiguration(int index) { return configuration_.get(index); } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public com.google.protobuf.ByteString getConfigurationBytes(int index) { return configuration_.getByteString(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (index_ != 0L) { output.writeUInt64(1, index_); } if (term_ != 0L) { output.writeUInt64(2, term_); } if (type_ != ai.eloquent.raft.EloquentRaftProto.LogEntryType.TRANSITION.getNumber()) { output.writeEnum(3, type_); } if (payloadCase_ == 4) { output.writeBytes( 4, (com.google.protobuf.ByteString) payload_); } for (int i = 0; i < configuration_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, configuration_.getRaw(i)); } if (payloadCase_ == 6) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, payload_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (index_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, index_); } if (term_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(2, term_); } if (type_ != ai.eloquent.raft.EloquentRaftProto.LogEntryType.TRANSITION.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(3, type_); } if (payloadCase_ == 4) { size += com.google.protobuf.CodedOutputStream .computeBytesSize( 4, (com.google.protobuf.ByteString) payload_); } { int dataSize = 0; for (int i = 0; i < configuration_.size(); i++) { dataSize += computeStringSizeNoTag(configuration_.getRaw(i)); } size += dataSize; size += 1 * getConfigurationList().size(); } if (payloadCase_ == 6) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, payload_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.LogEntry)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.LogEntry other = (ai.eloquent.raft.EloquentRaftProto.LogEntry) obj; boolean result = true; result = result && (getIndex() == other.getIndex()); result = result && (getTerm() == other.getTerm()); result = result && type_ == other.type_; result = result && getConfigurationList() .equals(other.getConfigurationList()); result = result && getPayloadCase().equals( other.getPayloadCase()); if (!result) return false; switch (payloadCase_) { case 4: result = result && getTransition() .equals(other.getTransition()); break; case 6: result = result && getNewHospiceMember() .equals(other.getNewHospiceMember()); break; case 0: default: } result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + INDEX_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getIndex()); hash = (37 * hash) + TERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTerm()); hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; if (getConfigurationCount() > 0) { hash = (37 * hash) + CONFIGURATION_FIELD_NUMBER; hash = (53 * hash) + getConfigurationList().hashCode(); } switch (payloadCase_) { case 4: hash = (37 * hash) + TRANSITION_FIELD_NUMBER; hash = (53 * hash) + getTransition().hashCode(); break; case 6: hash = (37 * hash) + NEW_HOSPICE_MEMBER_FIELD_NUMBER; hash = (53 * hash) + getNewHospiceMember().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.LogEntry prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.LogEntry} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.LogEntry) ai.eloquent.raft.EloquentRaftProto.LogEntryOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LogEntry_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LogEntry_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.LogEntry.class, ai.eloquent.raft.EloquentRaftProto.LogEntry.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.LogEntry.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); index_ = 0L; term_ = 0L; type_ = 0; configuration_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000020); payloadCase_ = 0; payload_ = null; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LogEntry_descriptor; } public ai.eloquent.raft.EloquentRaftProto.LogEntry getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.LogEntry.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.LogEntry build() { ai.eloquent.raft.EloquentRaftProto.LogEntry result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.LogEntry buildPartial() { ai.eloquent.raft.EloquentRaftProto.LogEntry result = new ai.eloquent.raft.EloquentRaftProto.LogEntry(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.index_ = index_; result.term_ = term_; result.type_ = type_; if (payloadCase_ == 4) { result.payload_ = payload_; } if (payloadCase_ == 6) { result.payload_ = payload_; } if (((bitField0_ & 0x00000020) == 0x00000020)) { configuration_ = configuration_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000020); } result.configuration_ = configuration_; result.bitField0_ = to_bitField0_; result.payloadCase_ = payloadCase_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.LogEntry) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.LogEntry)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.LogEntry other) { if (other == ai.eloquent.raft.EloquentRaftProto.LogEntry.getDefaultInstance()) return this; if (other.getIndex() != 0L) { setIndex(other.getIndex()); } if (other.getTerm() != 0L) { setTerm(other.getTerm()); } if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } if (!other.configuration_.isEmpty()) { if (configuration_.isEmpty()) { configuration_ = other.configuration_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensureConfigurationIsMutable(); configuration_.addAll(other.configuration_); } onChanged(); } switch (other.getPayloadCase()) { case TRANSITION: { setTransition(other.getTransition()); break; } case NEW_HOSPICE_MEMBER: { payloadCase_ = 6; payload_ = other.payload_; onChanged(); break; } case PAYLOAD_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.LogEntry parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.LogEntry) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int payloadCase_ = 0; private java.lang.Object payload_; public PayloadCase getPayloadCase() { return PayloadCase.forNumber( payloadCase_); } public Builder clearPayload() { payloadCase_ = 0; payload_ = null; onChanged(); return this; } private int bitField0_; private long index_ ; /** * <pre> * the index of the log entry * </pre> * * <code>uint64 index = 1;</code> */ public long getIndex() { return index_; } /** * <pre> * the index of the log entry * </pre> * * <code>uint64 index = 1;</code> */ public Builder setIndex(long value) { index_ = value; onChanged(); return this; } /** * <pre> * the index of the log entry * </pre> * * <code>uint64 index = 1;</code> */ public Builder clearIndex() { index_ = 0L; onChanged(); return this; } private long term_ ; /** * <pre> * term when the log entry was created * </pre> * * <code>uint64 term = 2;</code> */ public long getTerm() { return term_; } /** * <pre> * term when the log entry was created * </pre> * * <code>uint64 term = 2;</code> */ public Builder setTerm(long value) { term_ = value; onChanged(); return this; } /** * <pre> * term when the log entry was created * </pre> * * <code>uint64 term = 2;</code> */ public Builder clearTerm() { term_ = 0L; onChanged(); return this; } private int type_ = 0; /** * <pre> * the type of the log entry * </pre> * * <code>.ai.eloquent.raft.LogEntryType type = 3;</code> */ public int getTypeValue() { return type_; } /** * <pre> * the type of the log entry * </pre> * * <code>.ai.eloquent.raft.LogEntryType type = 3;</code> */ public Builder setTypeValue(int value) { type_ = value; onChanged(); return this; } /** * <pre> * the type of the log entry * </pre> * * <code>.ai.eloquent.raft.LogEntryType type = 3;</code> */ public ai.eloquent.raft.EloquentRaftProto.LogEntryType getType() { ai.eloquent.raft.EloquentRaftProto.LogEntryType result = ai.eloquent.raft.EloquentRaftProto.LogEntryType.valueOf(type_); return result == null ? ai.eloquent.raft.EloquentRaftProto.LogEntryType.UNRECOGNIZED : result; } /** * <pre> * the type of the log entry * </pre> * * <code>.ai.eloquent.raft.LogEntryType type = 3;</code> */ public Builder setType(ai.eloquent.raft.EloquentRaftProto.LogEntryType value) { if (value == null) { throw new NullPointerException(); } type_ = value.getNumber(); onChanged(); return this; } /** * <pre> * the type of the log entry * </pre> * * <code>.ai.eloquent.raft.LogEntryType type = 3;</code> */ public Builder clearType() { type_ = 0; onChanged(); return this; } /** * <pre> * the raw bytes of the transition request - only in TRANSITION messages * </pre> * * <code>bytes transition = 4;</code> */ public com.google.protobuf.ByteString getTransition() { if (payloadCase_ == 4) { return (com.google.protobuf.ByteString) payload_; } return com.google.protobuf.ByteString.EMPTY; } /** * <pre> * the raw bytes of the transition request - only in TRANSITION messages * </pre> * * <code>bytes transition = 4;</code> */ public Builder setTransition(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } payloadCase_ = 4; payload_ = value; onChanged(); return this; } /** * <pre> * the raw bytes of the transition request - only in TRANSITION messages * </pre> * * <code>bytes transition = 4;</code> */ public Builder clearTransition() { if (payloadCase_ == 4) { payloadCase_ = 0; payload_ = null; onChanged(); } return this; } /** * <pre> * or, the addition of a hospice member - only in TRANSITION messages * </pre> * * <code>string new_hospice_member = 6;</code> */ public java.lang.String getNewHospiceMember() { java.lang.Object ref = ""; if (payloadCase_ == 6) { ref = payload_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (payloadCase_ == 6) { payload_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <pre> * or, the addition of a hospice member - only in TRANSITION messages * </pre> * * <code>string new_hospice_member = 6;</code> */ public com.google.protobuf.ByteString getNewHospiceMemberBytes() { java.lang.Object ref = ""; if (payloadCase_ == 6) { ref = payload_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (payloadCase_ == 6) { payload_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * or, the addition of a hospice member - only in TRANSITION messages * </pre> * * <code>string new_hospice_member = 6;</code> */ public Builder setNewHospiceMember( java.lang.String value) { if (value == null) { throw new NullPointerException(); } payloadCase_ = 6; payload_ = value; onChanged(); return this; } /** * <pre> * or, the addition of a hospice member - only in TRANSITION messages * </pre> * * <code>string new_hospice_member = 6;</code> */ public Builder clearNewHospiceMember() { if (payloadCase_ == 6) { payloadCase_ = 0; payload_ = null; onChanged(); } return this; } /** * <pre> * or, the addition of a hospice member - only in TRANSITION messages * </pre> * * <code>string new_hospice_member = 6;</code> */ public Builder setNewHospiceMemberBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); payloadCase_ = 6; payload_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList configuration_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureConfigurationIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { configuration_ = new com.google.protobuf.LazyStringArrayList(configuration_); bitField0_ |= 0x00000020; } } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public com.google.protobuf.ProtocolStringList getConfigurationList() { return configuration_.getUnmodifiableView(); } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public int getConfigurationCount() { return configuration_.size(); } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public java.lang.String getConfiguration(int index) { return configuration_.get(index); } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public com.google.protobuf.ByteString getConfigurationBytes(int index) { return configuration_.getByteString(index); } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public Builder setConfiguration( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureConfigurationIsMutable(); configuration_.set(index, value); onChanged(); return this; } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public Builder addConfiguration( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureConfigurationIsMutable(); configuration_.add(value); onChanged(); return this; } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public Builder addAllConfiguration( java.lang.Iterable<java.lang.String> values) { ensureConfigurationIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, configuration_); onChanged(); return this; } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public Builder clearConfiguration() { configuration_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000020); onChanged(); return this; } /** * <pre> * the new configuration for the cluster - only in CONFIGURATION * </pre> * * <code>repeated string configuration = 5;</code> */ public Builder addConfigurationBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureConfigurationIsMutable(); configuration_.add(value); onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.LogEntry) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.LogEntry) private static final ai.eloquent.raft.EloquentRaftProto.LogEntry DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.LogEntry(); } public static ai.eloquent.raft.EloquentRaftProto.LogEntry getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<LogEntry> PARSER = new com.google.protobuf.AbstractParser<LogEntry>() { public LogEntry parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new LogEntry(input, extensionRegistry); } }; public static com.google.protobuf.Parser<LogEntry> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<LogEntry> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.LogEntry getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface AddServerRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.AddServerRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> ** the name of the new server to add to the configuration * </pre> * * <code>string newServer = 1;</code> */ java.lang.String getNewServer(); /** * <pre> ** the name of the new server to add to the configuration * </pre> * * <code>string newServer = 1;</code> */ com.google.protobuf.ByteString getNewServerBytes(); /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ java.util.List<java.lang.String> getQuorumList(); /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ int getQuorumCount(); /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ java.lang.String getQuorum(int index); /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ com.google.protobuf.ByteString getQuorumBytes(int index); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ java.util.List<java.lang.String> getForwardedByList(); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ int getForwardedByCount(); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ java.lang.String getForwardedBy(int index); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ com.google.protobuf.ByteString getForwardedByBytes(int index); } /** * Protobuf type {@code ai.eloquent.raft.AddServerRequest} */ public static final class AddServerRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.AddServerRequest) AddServerRequestOrBuilder { private static final long serialVersionUID = 0L; // Use AddServerRequest.newBuilder() to construct. private AddServerRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AddServerRequest() { newServer_ = ""; quorum_ = com.google.protobuf.LazyStringArrayList.EMPTY; forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private AddServerRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); newServer_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { quorum_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000002; } quorum_.add(s); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { forwardedBy_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000004; } forwardedBy_.add(s); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { quorum_ = quorum_.getUnmodifiableView(); } if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { forwardedBy_ = forwardedBy_.getUnmodifiableView(); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AddServerRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AddServerRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.AddServerRequest.class, ai.eloquent.raft.EloquentRaftProto.AddServerRequest.Builder.class); } private int bitField0_; public static final int NEWSERVER_FIELD_NUMBER = 1; private volatile java.lang.Object newServer_; /** * <pre> ** the name of the new server to add to the configuration * </pre> * * <code>string newServer = 1;</code> */ public java.lang.String getNewServer() { java.lang.Object ref = newServer_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); newServer_ = s; return s; } } /** * <pre> ** the name of the new server to add to the configuration * </pre> * * <code>string newServer = 1;</code> */ public com.google.protobuf.ByteString getNewServerBytes() { java.lang.Object ref = newServer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); newServer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int QUORUM_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList quorum_; /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public com.google.protobuf.ProtocolStringList getQuorumList() { return quorum_; } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public int getQuorumCount() { return quorum_.size(); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public java.lang.String getQuorum(int index) { return quorum_.get(index); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public com.google.protobuf.ByteString getQuorumBytes(int index) { return quorum_.getByteString(index); } public static final int FORWARDEDBY_FIELD_NUMBER = 3; private com.google.protobuf.LazyStringList forwardedBy_; /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ProtocolStringList getForwardedByList() { return forwardedBy_; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public int getForwardedByCount() { return forwardedBy_.size(); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public java.lang.String getForwardedBy(int index) { return forwardedBy_.get(index); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ByteString getForwardedByBytes(int index) { return forwardedBy_.getByteString(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNewServerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, newServer_); } for (int i = 0; i < quorum_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, quorum_.getRaw(i)); } for (int i = 0; i < forwardedBy_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, forwardedBy_.getRaw(i)); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNewServerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, newServer_); } { int dataSize = 0; for (int i = 0; i < quorum_.size(); i++) { dataSize += computeStringSizeNoTag(quorum_.getRaw(i)); } size += dataSize; size += 1 * getQuorumList().size(); } { int dataSize = 0; for (int i = 0; i < forwardedBy_.size(); i++) { dataSize += computeStringSizeNoTag(forwardedBy_.getRaw(i)); } size += dataSize; size += 1 * getForwardedByList().size(); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.AddServerRequest)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.AddServerRequest other = (ai.eloquent.raft.EloquentRaftProto.AddServerRequest) obj; boolean result = true; result = result && getNewServer() .equals(other.getNewServer()); result = result && getQuorumList() .equals(other.getQuorumList()); result = result && getForwardedByList() .equals(other.getForwardedByList()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NEWSERVER_FIELD_NUMBER; hash = (53 * hash) + getNewServer().hashCode(); if (getQuorumCount() > 0) { hash = (37 * hash) + QUORUM_FIELD_NUMBER; hash = (53 * hash) + getQuorumList().hashCode(); } if (getForwardedByCount() > 0) { hash = (37 * hash) + FORWARDEDBY_FIELD_NUMBER; hash = (53 * hash) + getForwardedByList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.AddServerRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.AddServerRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.AddServerRequest) ai.eloquent.raft.EloquentRaftProto.AddServerRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AddServerRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AddServerRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.AddServerRequest.class, ai.eloquent.raft.EloquentRaftProto.AddServerRequest.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.AddServerRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); newServer_ = ""; quorum_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AddServerRequest_descriptor; } public ai.eloquent.raft.EloquentRaftProto.AddServerRequest getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.AddServerRequest.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.AddServerRequest build() { ai.eloquent.raft.EloquentRaftProto.AddServerRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.AddServerRequest buildPartial() { ai.eloquent.raft.EloquentRaftProto.AddServerRequest result = new ai.eloquent.raft.EloquentRaftProto.AddServerRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.newServer_ = newServer_; if (((bitField0_ & 0x00000002) == 0x00000002)) { quorum_ = quorum_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000002); } result.quorum_ = quorum_; if (((bitField0_ & 0x00000004) == 0x00000004)) { forwardedBy_ = forwardedBy_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000004); } result.forwardedBy_ = forwardedBy_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.AddServerRequest) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.AddServerRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.AddServerRequest other) { if (other == ai.eloquent.raft.EloquentRaftProto.AddServerRequest.getDefaultInstance()) return this; if (!other.getNewServer().isEmpty()) { newServer_ = other.newServer_; onChanged(); } if (!other.quorum_.isEmpty()) { if (quorum_.isEmpty()) { quorum_ = other.quorum_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureQuorumIsMutable(); quorum_.addAll(other.quorum_); } onChanged(); } if (!other.forwardedBy_.isEmpty()) { if (forwardedBy_.isEmpty()) { forwardedBy_ = other.forwardedBy_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureForwardedByIsMutable(); forwardedBy_.addAll(other.forwardedBy_); } onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.AddServerRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.AddServerRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object newServer_ = ""; /** * <pre> ** the name of the new server to add to the configuration * </pre> * * <code>string newServer = 1;</code> */ public java.lang.String getNewServer() { java.lang.Object ref = newServer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); newServer_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** the name of the new server to add to the configuration * </pre> * * <code>string newServer = 1;</code> */ public com.google.protobuf.ByteString getNewServerBytes() { java.lang.Object ref = newServer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); newServer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** the name of the new server to add to the configuration * </pre> * * <code>string newServer = 1;</code> */ public Builder setNewServer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } newServer_ = value; onChanged(); return this; } /** * <pre> ** the name of the new server to add to the configuration * </pre> * * <code>string newServer = 1;</code> */ public Builder clearNewServer() { newServer_ = getDefaultInstance().getNewServer(); onChanged(); return this; } /** * <pre> ** the name of the new server to add to the configuration * </pre> * * <code>string newServer = 1;</code> */ public Builder setNewServerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); newServer_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList quorum_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureQuorumIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { quorum_ = new com.google.protobuf.LazyStringArrayList(quorum_); bitField0_ |= 0x00000002; } } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public com.google.protobuf.ProtocolStringList getQuorumList() { return quorum_.getUnmodifiableView(); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public int getQuorumCount() { return quorum_.size(); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public java.lang.String getQuorum(int index) { return quorum_.get(index); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public com.google.protobuf.ByteString getQuorumBytes(int index) { return quorum_.getByteString(index); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public Builder setQuorum( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureQuorumIsMutable(); quorum_.set(index, value); onChanged(); return this; } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public Builder addQuorum( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureQuorumIsMutable(); quorum_.add(value); onChanged(); return this; } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public Builder addAllQuorum( java.lang.Iterable<java.lang.String> values) { ensureQuorumIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, quorum_); onChanged(); return this; } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public Builder clearQuorum() { quorum_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public Builder addQuorumBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureQuorumIsMutable(); quorum_.add(value); onChanged(); return this; } private com.google.protobuf.LazyStringList forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureForwardedByIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { forwardedBy_ = new com.google.protobuf.LazyStringArrayList(forwardedBy_); bitField0_ |= 0x00000004; } } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ProtocolStringList getForwardedByList() { return forwardedBy_.getUnmodifiableView(); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public int getForwardedByCount() { return forwardedBy_.size(); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public java.lang.String getForwardedBy(int index) { return forwardedBy_.get(index); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ByteString getForwardedByBytes(int index) { return forwardedBy_.getByteString(index); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder setForwardedBy( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureForwardedByIsMutable(); forwardedBy_.set(index, value); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder addForwardedBy( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureForwardedByIsMutable(); forwardedBy_.add(value); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder addAllForwardedBy( java.lang.Iterable<java.lang.String> values) { ensureForwardedByIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, forwardedBy_); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder clearForwardedBy() { forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder addForwardedByBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureForwardedByIsMutable(); forwardedBy_.add(value); onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.AddServerRequest) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.AddServerRequest) private static final ai.eloquent.raft.EloquentRaftProto.AddServerRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.AddServerRequest(); } public static ai.eloquent.raft.EloquentRaftProto.AddServerRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AddServerRequest> PARSER = new com.google.protobuf.AbstractParser<AddServerRequest>() { public AddServerRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new AddServerRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<AddServerRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AddServerRequest> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.AddServerRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface AddServerReplyOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.AddServerReply) com.google.protobuf.MessageOrBuilder { /** * <pre> * OK if the server was added successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ int getStatusValue(); /** * <pre> * OK if the server was added successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus getStatus(); /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ java.lang.String getLeadershipHint(); /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ com.google.protobuf.ByteString getLeadershipHintBytes(); } /** * Protobuf type {@code ai.eloquent.raft.AddServerReply} */ public static final class AddServerReply extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.AddServerReply) AddServerReplyOrBuilder { private static final long serialVersionUID = 0L; // Use AddServerReply.newBuilder() to construct. private AddServerReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AddServerReply() { status_ = 0; leadershipHint_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private AddServerReply( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { int rawValue = input.readEnum(); status_ = rawValue; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); leadershipHint_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AddServerReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AddServerReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.AddServerReply.class, ai.eloquent.raft.EloquentRaftProto.AddServerReply.Builder.class); } public static final int STATUS_FIELD_NUMBER = 1; private int status_; /** * <pre> * OK if the server was added successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public int getStatusValue() { return status_; } /** * <pre> * OK if the server was added successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus getStatus() { ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus result = ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.valueOf(status_); return result == null ? ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.UNRECOGNIZED : result; } public static final int LEADERSHIPHINT_FIELD_NUMBER = 2; private volatile java.lang.Object leadershipHint_; /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public java.lang.String getLeadershipHint() { java.lang.Object ref = leadershipHint_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); leadershipHint_ = s; return s; } } /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public com.google.protobuf.ByteString getLeadershipHintBytes() { java.lang.Object ref = leadershipHint_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); leadershipHint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (status_ != ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.OK.getNumber()) { output.writeEnum(1, status_); } if (!getLeadershipHintBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, leadershipHint_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (status_ != ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.OK.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, status_); } if (!getLeadershipHintBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, leadershipHint_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.AddServerReply)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.AddServerReply other = (ai.eloquent.raft.EloquentRaftProto.AddServerReply) obj; boolean result = true; result = result && status_ == other.status_; result = result && getLeadershipHint() .equals(other.getLeadershipHint()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (37 * hash) + LEADERSHIPHINT_FIELD_NUMBER; hash = (53 * hash) + getLeadershipHint().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.AddServerReply prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.AddServerReply} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.AddServerReply) ai.eloquent.raft.EloquentRaftProto.AddServerReplyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AddServerReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AddServerReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.AddServerReply.class, ai.eloquent.raft.EloquentRaftProto.AddServerReply.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.AddServerReply.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); status_ = 0; leadershipHint_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_AddServerReply_descriptor; } public ai.eloquent.raft.EloquentRaftProto.AddServerReply getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.AddServerReply.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.AddServerReply build() { ai.eloquent.raft.EloquentRaftProto.AddServerReply result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.AddServerReply buildPartial() { ai.eloquent.raft.EloquentRaftProto.AddServerReply result = new ai.eloquent.raft.EloquentRaftProto.AddServerReply(this); result.status_ = status_; result.leadershipHint_ = leadershipHint_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.AddServerReply) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.AddServerReply)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.AddServerReply other) { if (other == ai.eloquent.raft.EloquentRaftProto.AddServerReply.getDefaultInstance()) return this; if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } if (!other.getLeadershipHint().isEmpty()) { leadershipHint_ = other.leadershipHint_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.AddServerReply parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.AddServerReply) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int status_ = 0; /** * <pre> * OK if the server was added successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public int getStatusValue() { return status_; } /** * <pre> * OK if the server was added successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public Builder setStatusValue(int value) { status_ = value; onChanged(); return this; } /** * <pre> * OK if the server was added successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus getStatus() { ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus result = ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.valueOf(status_); return result == null ? ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.UNRECOGNIZED : result; } /** * <pre> * OK if the server was added successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public Builder setStatus(ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus value) { if (value == null) { throw new NullPointerException(); } status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * OK if the server was added successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public Builder clearStatus() { status_ = 0; onChanged(); return this; } private java.lang.Object leadershipHint_ = ""; /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public java.lang.String getLeadershipHint() { java.lang.Object ref = leadershipHint_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); leadershipHint_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public com.google.protobuf.ByteString getLeadershipHintBytes() { java.lang.Object ref = leadershipHint_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); leadershipHint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public Builder setLeadershipHint( java.lang.String value) { if (value == null) { throw new NullPointerException(); } leadershipHint_ = value; onChanged(); return this; } /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public Builder clearLeadershipHint() { leadershipHint_ = getDefaultInstance().getLeadershipHint(); onChanged(); return this; } /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public Builder setLeadershipHintBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); leadershipHint_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.AddServerReply) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.AddServerReply) private static final ai.eloquent.raft.EloquentRaftProto.AddServerReply DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.AddServerReply(); } public static ai.eloquent.raft.EloquentRaftProto.AddServerReply getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AddServerReply> PARSER = new com.google.protobuf.AbstractParser<AddServerReply>() { public AddServerReply parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new AddServerReply(input, extensionRegistry); } }; public static com.google.protobuf.Parser<AddServerReply> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AddServerReply> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.AddServerReply getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface RemoveServerRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.RemoveServerRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> ** the name of the server to remove from the configuration * </pre> * * <code>string oldServer = 1;</code> */ java.lang.String getOldServer(); /** * <pre> ** the name of the server to remove from the configuration * </pre> * * <code>string oldServer = 1;</code> */ com.google.protobuf.ByteString getOldServerBytes(); /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ java.util.List<java.lang.String> getQuorumList(); /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ int getQuorumCount(); /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ java.lang.String getQuorum(int index); /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ com.google.protobuf.ByteString getQuorumBytes(int index); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ java.util.List<java.lang.String> getForwardedByList(); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ int getForwardedByCount(); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ java.lang.String getForwardedBy(int index); /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ com.google.protobuf.ByteString getForwardedByBytes(int index); } /** * Protobuf type {@code ai.eloquent.raft.RemoveServerRequest} */ public static final class RemoveServerRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.RemoveServerRequest) RemoveServerRequestOrBuilder { private static final long serialVersionUID = 0L; // Use RemoveServerRequest.newBuilder() to construct. private RemoveServerRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RemoveServerRequest() { oldServer_ = ""; quorum_ = com.google.protobuf.LazyStringArrayList.EMPTY; forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private RemoveServerRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); oldServer_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { quorum_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000002; } quorum_.add(s); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { forwardedBy_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000004; } forwardedBy_.add(s); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { quorum_ = quorum_.getUnmodifiableView(); } if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { forwardedBy_ = forwardedBy_.getUnmodifiableView(); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RemoveServerRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RemoveServerRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.class, ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.Builder.class); } private int bitField0_; public static final int OLDSERVER_FIELD_NUMBER = 1; private volatile java.lang.Object oldServer_; /** * <pre> ** the name of the server to remove from the configuration * </pre> * * <code>string oldServer = 1;</code> */ public java.lang.String getOldServer() { java.lang.Object ref = oldServer_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); oldServer_ = s; return s; } } /** * <pre> ** the name of the server to remove from the configuration * </pre> * * <code>string oldServer = 1;</code> */ public com.google.protobuf.ByteString getOldServerBytes() { java.lang.Object ref = oldServer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); oldServer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int QUORUM_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList quorum_; /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public com.google.protobuf.ProtocolStringList getQuorumList() { return quorum_; } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public int getQuorumCount() { return quorum_.size(); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public java.lang.String getQuorum(int index) { return quorum_.get(index); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public com.google.protobuf.ByteString getQuorumBytes(int index) { return quorum_.getByteString(index); } public static final int FORWARDEDBY_FIELD_NUMBER = 3; private com.google.protobuf.LazyStringList forwardedBy_; /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ProtocolStringList getForwardedByList() { return forwardedBy_; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public int getForwardedByCount() { return forwardedBy_.size(); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public java.lang.String getForwardedBy(int index) { return forwardedBy_.get(index); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ByteString getForwardedByBytes(int index) { return forwardedBy_.getByteString(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getOldServerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, oldServer_); } for (int i = 0; i < quorum_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, quorum_.getRaw(i)); } for (int i = 0; i < forwardedBy_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, forwardedBy_.getRaw(i)); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getOldServerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, oldServer_); } { int dataSize = 0; for (int i = 0; i < quorum_.size(); i++) { dataSize += computeStringSizeNoTag(quorum_.getRaw(i)); } size += dataSize; size += 1 * getQuorumList().size(); } { int dataSize = 0; for (int i = 0; i < forwardedBy_.size(); i++) { dataSize += computeStringSizeNoTag(forwardedBy_.getRaw(i)); } size += dataSize; size += 1 * getForwardedByList().size(); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest other = (ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) obj; boolean result = true; result = result && getOldServer() .equals(other.getOldServer()); result = result && getQuorumList() .equals(other.getQuorumList()); result = result && getForwardedByList() .equals(other.getForwardedByList()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + OLDSERVER_FIELD_NUMBER; hash = (53 * hash) + getOldServer().hashCode(); if (getQuorumCount() > 0) { hash = (37 * hash) + QUORUM_FIELD_NUMBER; hash = (53 * hash) + getQuorumList().hashCode(); } if (getForwardedByCount() > 0) { hash = (37 * hash) + FORWARDEDBY_FIELD_NUMBER; hash = (53 * hash) + getForwardedByList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.RemoveServerRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.RemoveServerRequest) ai.eloquent.raft.EloquentRaftProto.RemoveServerRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RemoveServerRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RemoveServerRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.class, ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); oldServer_ = ""; quorum_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RemoveServerRequest_descriptor; } public ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest build() { ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest buildPartial() { ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest result = new ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.oldServer_ = oldServer_; if (((bitField0_ & 0x00000002) == 0x00000002)) { quorum_ = quorum_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000002); } result.quorum_ = quorum_; if (((bitField0_ & 0x00000004) == 0x00000004)) { forwardedBy_ = forwardedBy_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000004); } result.forwardedBy_ = forwardedBy_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest other) { if (other == ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest.getDefaultInstance()) return this; if (!other.getOldServer().isEmpty()) { oldServer_ = other.oldServer_; onChanged(); } if (!other.quorum_.isEmpty()) { if (quorum_.isEmpty()) { quorum_ = other.quorum_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureQuorumIsMutable(); quorum_.addAll(other.quorum_); } onChanged(); } if (!other.forwardedBy_.isEmpty()) { if (forwardedBy_.isEmpty()) { forwardedBy_ = other.forwardedBy_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureForwardedByIsMutable(); forwardedBy_.addAll(other.forwardedBy_); } onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object oldServer_ = ""; /** * <pre> ** the name of the server to remove from the configuration * </pre> * * <code>string oldServer = 1;</code> */ public java.lang.String getOldServer() { java.lang.Object ref = oldServer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); oldServer_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> ** the name of the server to remove from the configuration * </pre> * * <code>string oldServer = 1;</code> */ public com.google.protobuf.ByteString getOldServerBytes() { java.lang.Object ref = oldServer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); oldServer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> ** the name of the server to remove from the configuration * </pre> * * <code>string oldServer = 1;</code> */ public Builder setOldServer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } oldServer_ = value; onChanged(); return this; } /** * <pre> ** the name of the server to remove from the configuration * </pre> * * <code>string oldServer = 1;</code> */ public Builder clearOldServer() { oldServer_ = getDefaultInstance().getOldServer(); onChanged(); return this; } /** * <pre> ** the name of the server to remove from the configuration * </pre> * * <code>string oldServer = 1;</code> */ public Builder setOldServerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); oldServer_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList quorum_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureQuorumIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { quorum_ = new com.google.protobuf.LazyStringArrayList(quorum_); bitField0_ |= 0x00000002; } } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public com.google.protobuf.ProtocolStringList getQuorumList() { return quorum_.getUnmodifiableView(); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public int getQuorumCount() { return quorum_.size(); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public java.lang.String getQuorum(int index) { return quorum_.get(index); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public com.google.protobuf.ByteString getQuorumBytes(int index) { return quorum_.getByteString(index); } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public Builder setQuorum( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureQuorumIsMutable(); quorum_.set(index, value); onChanged(); return this; } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public Builder addQuorum( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureQuorumIsMutable(); quorum_.add(value); onChanged(); return this; } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public Builder addAllQuorum( java.lang.Iterable<java.lang.String> values) { ensureQuorumIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, quorum_); onChanged(); return this; } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public Builder clearQuorum() { quorum_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> ** NOT STANDARD RAFT: The set of servers in the new configuration. This is just a sanity check. * </pre> * * <code>repeated string quorum = 2;</code> */ public Builder addQuorumBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureQuorumIsMutable(); quorum_.add(value); onChanged(); return this; } private com.google.protobuf.LazyStringList forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureForwardedByIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { forwardedBy_ = new com.google.protobuf.LazyStringArrayList(forwardedBy_); bitField0_ |= 0x00000004; } } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ProtocolStringList getForwardedByList() { return forwardedBy_.getUnmodifiableView(); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public int getForwardedByCount() { return forwardedBy_.size(); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public java.lang.String getForwardedBy(int index) { return forwardedBy_.get(index); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public com.google.protobuf.ByteString getForwardedByBytes(int index) { return forwardedBy_.getByteString(index); } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder setForwardedBy( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureForwardedByIsMutable(); forwardedBy_.set(index, value); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder addForwardedBy( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureForwardedByIsMutable(); forwardedBy_.add(value); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder addAllForwardedBy( java.lang.Iterable<java.lang.String> values) { ensureForwardedByIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, forwardedBy_); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder clearForwardedBy() { forwardedBy_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * the nodes that this request has already been forwarded through, for loop detection * </pre> * * <code>repeated string forwardedBy = 3;</code> */ public Builder addForwardedByBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureForwardedByIsMutable(); forwardedBy_.add(value); onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.RemoveServerRequest) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.RemoveServerRequest) private static final ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest(); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RemoveServerRequest> PARSER = new com.google.protobuf.AbstractParser<RemoveServerRequest>() { public RemoveServerRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new RemoveServerRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<RemoveServerRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RemoveServerRequest> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.RemoveServerRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface RemoveServerReplyOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.RemoveServerReply) com.google.protobuf.MessageOrBuilder { /** * <pre> * OK if the server was removed successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ int getStatusValue(); /** * <pre> * OK if the server was removed successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus getStatus(); /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ java.lang.String getLeadershipHint(); /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ com.google.protobuf.ByteString getLeadershipHintBytes(); } /** * Protobuf type {@code ai.eloquent.raft.RemoveServerReply} */ public static final class RemoveServerReply extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.RemoveServerReply) RemoveServerReplyOrBuilder { private static final long serialVersionUID = 0L; // Use RemoveServerReply.newBuilder() to construct. private RemoveServerReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RemoveServerReply() { status_ = 0; leadershipHint_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private RemoveServerReply( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { int rawValue = input.readEnum(); status_ = rawValue; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); leadershipHint_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RemoveServerReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RemoveServerReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.class, ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.Builder.class); } public static final int STATUS_FIELD_NUMBER = 1; private int status_; /** * <pre> * OK if the server was removed successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public int getStatusValue() { return status_; } /** * <pre> * OK if the server was removed successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus getStatus() { ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus result = ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.valueOf(status_); return result == null ? ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.UNRECOGNIZED : result; } public static final int LEADERSHIPHINT_FIELD_NUMBER = 2; private volatile java.lang.Object leadershipHint_; /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public java.lang.String getLeadershipHint() { java.lang.Object ref = leadershipHint_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); leadershipHint_ = s; return s; } } /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public com.google.protobuf.ByteString getLeadershipHintBytes() { java.lang.Object ref = leadershipHint_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); leadershipHint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (status_ != ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.OK.getNumber()) { output.writeEnum(1, status_); } if (!getLeadershipHintBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, leadershipHint_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (status_ != ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.OK.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, status_); } if (!getLeadershipHintBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, leadershipHint_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.RemoveServerReply)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.RemoveServerReply other = (ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) obj; boolean result = true; result = result && status_ == other.status_; result = result && getLeadershipHint() .equals(other.getLeadershipHint()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (37 * hash) + LEADERSHIPHINT_FIELD_NUMBER; hash = (53 * hash) + getLeadershipHint().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.RemoveServerReply prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.RemoveServerReply} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.RemoveServerReply) ai.eloquent.raft.EloquentRaftProto.RemoveServerReplyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RemoveServerReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RemoveServerReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.class, ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); status_ = 0; leadershipHint_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_RemoveServerReply_descriptor; } public ai.eloquent.raft.EloquentRaftProto.RemoveServerReply getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.RemoveServerReply build() { ai.eloquent.raft.EloquentRaftProto.RemoveServerReply result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.RemoveServerReply buildPartial() { ai.eloquent.raft.EloquentRaftProto.RemoveServerReply result = new ai.eloquent.raft.EloquentRaftProto.RemoveServerReply(this); result.status_ = status_; result.leadershipHint_ = leadershipHint_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.RemoveServerReply)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.RemoveServerReply other) { if (other == ai.eloquent.raft.EloquentRaftProto.RemoveServerReply.getDefaultInstance()) return this; if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } if (!other.getLeadershipHint().isEmpty()) { leadershipHint_ = other.leadershipHint_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.RemoveServerReply parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.RemoveServerReply) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int status_ = 0; /** * <pre> * OK if the server was removed successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public int getStatusValue() { return status_; } /** * <pre> * OK if the server was removed successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public Builder setStatusValue(int value) { status_ = value; onChanged(); return this; } /** * <pre> * OK if the server was removed successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus getStatus() { ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus result = ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.valueOf(status_); return result == null ? ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus.UNRECOGNIZED : result; } /** * <pre> * OK if the server was removed successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public Builder setStatus(ai.eloquent.raft.EloquentRaftProto.MembershipChangeStatus value) { if (value == null) { throw new NullPointerException(); } status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * OK if the server was removed successfully * </pre> * * <code>.ai.eloquent.raft.MembershipChangeStatus status = 1;</code> */ public Builder clearStatus() { status_ = 0; onChanged(); return this; } private java.lang.Object leadershipHint_ = ""; /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public java.lang.String getLeadershipHint() { java.lang.Object ref = leadershipHint_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); leadershipHint_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public com.google.protobuf.ByteString getLeadershipHintBytes() { java.lang.Object ref = leadershipHint_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); leadershipHint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public Builder setLeadershipHint( java.lang.String value) { if (value == null) { throw new NullPointerException(); } leadershipHint_ = value; onChanged(); return this; } /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public Builder clearLeadershipHint() { leadershipHint_ = getDefaultInstance().getLeadershipHint(); onChanged(); return this; } /** * <pre> * address of recent leader, if known * </pre> * * <code>string leadershipHint = 2;</code> */ public Builder setLeadershipHintBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); leadershipHint_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.RemoveServerReply) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.RemoveServerReply) private static final ai.eloquent.raft.EloquentRaftProto.RemoveServerReply DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.RemoveServerReply(); } public static ai.eloquent.raft.EloquentRaftProto.RemoveServerReply getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RemoveServerReply> PARSER = new com.google.protobuf.AbstractParser<RemoveServerReply>() { public RemoveServerReply parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new RemoveServerReply(input, extensionRegistry); } }; public static com.google.protobuf.Parser<RemoveServerReply> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RemoveServerReply> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.RemoveServerReply getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface LivenessCheckRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.LivenessCheckRequest) com.google.protobuf.MessageOrBuilder { } /** * Protobuf type {@code ai.eloquent.raft.LivenessCheckRequest} */ public static final class LivenessCheckRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.LivenessCheckRequest) LivenessCheckRequestOrBuilder { private static final long serialVersionUID = 0L; // Use LivenessCheckRequest.newBuilder() to construct. private LivenessCheckRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private LivenessCheckRequest() { } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private LivenessCheckRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LivenessCheckRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LivenessCheckRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest.class, ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest.Builder.class); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest other = (ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest) obj; boolean result = true; result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.LivenessCheckRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.LivenessCheckRequest) ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LivenessCheckRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LivenessCheckRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest.class, ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LivenessCheckRequest_descriptor; } public ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest build() { ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest buildPartial() { ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest result = new ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest(this); onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest other) { if (other == ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.LivenessCheckRequest) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.LivenessCheckRequest) private static final ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest(); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<LivenessCheckRequest> PARSER = new com.google.protobuf.AbstractParser<LivenessCheckRequest>() { public LivenessCheckRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new LivenessCheckRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<LivenessCheckRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<LivenessCheckRequest> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.LivenessCheckRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface LivenessCheckReplyOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.LivenessCheckReply) com.google.protobuf.MessageOrBuilder { /** * <pre> * False if we're currently shutting down or booting up, true otherwise * </pre> * * <code>bool live = 1;</code> */ boolean getLive(); } /** * Protobuf type {@code ai.eloquent.raft.LivenessCheckReply} */ public static final class LivenessCheckReply extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.LivenessCheckReply) LivenessCheckReplyOrBuilder { private static final long serialVersionUID = 0L; // Use LivenessCheckReply.newBuilder() to construct. private LivenessCheckReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private LivenessCheckReply() { live_ = false; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private LivenessCheckReply( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { live_ = input.readBool(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LivenessCheckReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LivenessCheckReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply.class, ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply.Builder.class); } public static final int LIVE_FIELD_NUMBER = 1; private boolean live_; /** * <pre> * False if we're currently shutting down or booting up, true otherwise * </pre> * * <code>bool live = 1;</code> */ public boolean getLive() { return live_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (live_ != false) { output.writeBool(1, live_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (live_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(1, live_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply other = (ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply) obj; boolean result = true; result = result && (getLive() == other.getLive()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LIVE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getLive()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.LivenessCheckReply} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.LivenessCheckReply) ai.eloquent.raft.EloquentRaftProto.LivenessCheckReplyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LivenessCheckReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LivenessCheckReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply.class, ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); live_ = false; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_LivenessCheckReply_descriptor; } public ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply build() { ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply buildPartial() { ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply result = new ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply(this); result.live_ = live_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply other) { if (other == ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply.getDefaultInstance()) return this; if (other.getLive() != false) { setLive(other.getLive()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private boolean live_ ; /** * <pre> * False if we're currently shutting down or booting up, true otherwise * </pre> * * <code>bool live = 1;</code> */ public boolean getLive() { return live_; } /** * <pre> * False if we're currently shutting down or booting up, true otherwise * </pre> * * <code>bool live = 1;</code> */ public Builder setLive(boolean value) { live_ = value; onChanged(); return this; } /** * <pre> * False if we're currently shutting down or booting up, true otherwise * </pre> * * <code>bool live = 1;</code> */ public Builder clearLive() { live_ = false; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.LivenessCheckReply) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.LivenessCheckReply) private static final ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply(); } public static ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<LivenessCheckReply> PARSER = new com.google.protobuf.AbstractParser<LivenessCheckReply>() { public LivenessCheckReply parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new LivenessCheckReply(input, extensionRegistry); } }; public static com.google.protobuf.Parser<LivenessCheckReply> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<LivenessCheckReply> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.LivenessCheckReply getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface InstallSnapshotRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.InstallSnapshotRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * Leader's term * </pre> * * <code>uint64 term = 1;</code> */ long getTerm(); /** * <pre> * So the follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ java.lang.String getLeaderName(); /** * <pre> * So the follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ com.google.protobuf.ByteString getLeaderNameBytes(); /** * <pre> * The snapshot replaces all entries up through and including this index * </pre> * * <code>uint64 lastIndex = 3;</code> */ long getLastIndex(); /** * <pre> * The term of lastIndex * </pre> * * <code>uint64 lastTerm = 4;</code> */ long getLastTerm(); /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ java.util.List<java.lang.String> getLastConfigList(); /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ int getLastConfigCount(); /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ java.lang.String getLastConfig(int index); /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ com.google.protobuf.ByteString getLastConfigBytes(int index); /** * <pre> * raw bytes of the snapshot * </pre> * * <code>bytes data = 6;</code> */ com.google.protobuf.ByteString getData(); } /** * Protobuf type {@code ai.eloquent.raft.InstallSnapshotRequest} */ public static final class InstallSnapshotRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.InstallSnapshotRequest) InstallSnapshotRequestOrBuilder { private static final long serialVersionUID = 0L; // Use InstallSnapshotRequest.newBuilder() to construct. private InstallSnapshotRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private InstallSnapshotRequest() { term_ = 0L; leaderName_ = ""; lastIndex_ = 0L; lastTerm_ = 0L; lastConfig_ = com.google.protobuf.LazyStringArrayList.EMPTY; data_ = com.google.protobuf.ByteString.EMPTY; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private InstallSnapshotRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { term_ = input.readUInt64(); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); leaderName_ = s; break; } case 24: { lastIndex_ = input.readUInt64(); break; } case 32: { lastTerm_ = input.readUInt64(); break; } case 42: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) { lastConfig_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000010; } lastConfig_.add(s); break; } case 50: { data_ = input.readBytes(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000010) == 0x00000010)) { lastConfig_ = lastConfig_.getUnmodifiableView(); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_InstallSnapshotRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_InstallSnapshotRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.class, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.Builder.class); } private int bitField0_; public static final int TERM_FIELD_NUMBER = 1; private long term_; /** * <pre> * Leader's term * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } public static final int LEADERNAME_FIELD_NUMBER = 2; private volatile java.lang.Object leaderName_; /** * <pre> * So the follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public java.lang.String getLeaderName() { java.lang.Object ref = leaderName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); leaderName_ = s; return s; } } /** * <pre> * So the follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public com.google.protobuf.ByteString getLeaderNameBytes() { java.lang.Object ref = leaderName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); leaderName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LASTINDEX_FIELD_NUMBER = 3; private long lastIndex_; /** * <pre> * The snapshot replaces all entries up through and including this index * </pre> * * <code>uint64 lastIndex = 3;</code> */ public long getLastIndex() { return lastIndex_; } public static final int LASTTERM_FIELD_NUMBER = 4; private long lastTerm_; /** * <pre> * The term of lastIndex * </pre> * * <code>uint64 lastTerm = 4;</code> */ public long getLastTerm() { return lastTerm_; } public static final int LASTCONFIG_FIELD_NUMBER = 5; private com.google.protobuf.LazyStringList lastConfig_; /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public com.google.protobuf.ProtocolStringList getLastConfigList() { return lastConfig_; } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public int getLastConfigCount() { return lastConfig_.size(); } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public java.lang.String getLastConfig(int index) { return lastConfig_.get(index); } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public com.google.protobuf.ByteString getLastConfigBytes(int index) { return lastConfig_.getByteString(index); } public static final int DATA_FIELD_NUMBER = 6; private com.google.protobuf.ByteString data_; /** * <pre> * raw bytes of the snapshot * </pre> * * <code>bytes data = 6;</code> */ public com.google.protobuf.ByteString getData() { return data_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (term_ != 0L) { output.writeUInt64(1, term_); } if (!getLeaderNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, leaderName_); } if (lastIndex_ != 0L) { output.writeUInt64(3, lastIndex_); } if (lastTerm_ != 0L) { output.writeUInt64(4, lastTerm_); } for (int i = 0; i < lastConfig_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, lastConfig_.getRaw(i)); } if (!data_.isEmpty()) { output.writeBytes(6, data_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (term_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, term_); } if (!getLeaderNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, leaderName_); } if (lastIndex_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(3, lastIndex_); } if (lastTerm_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, lastTerm_); } { int dataSize = 0; for (int i = 0; i < lastConfig_.size(); i++) { dataSize += computeStringSizeNoTag(lastConfig_.getRaw(i)); } size += dataSize; size += 1 * getLastConfigList().size(); } if (!data_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(6, data_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest other = (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) obj; boolean result = true; result = result && (getTerm() == other.getTerm()); result = result && getLeaderName() .equals(other.getLeaderName()); result = result && (getLastIndex() == other.getLastIndex()); result = result && (getLastTerm() == other.getLastTerm()); result = result && getLastConfigList() .equals(other.getLastConfigList()); result = result && getData() .equals(other.getData()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTerm()); hash = (37 * hash) + LEADERNAME_FIELD_NUMBER; hash = (53 * hash) + getLeaderName().hashCode(); hash = (37 * hash) + LASTINDEX_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLastIndex()); hash = (37 * hash) + LASTTERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLastTerm()); if (getLastConfigCount() > 0) { hash = (37 * hash) + LASTCONFIG_FIELD_NUMBER; hash = (53 * hash) + getLastConfigList().hashCode(); } hash = (37 * hash) + DATA_FIELD_NUMBER; hash = (53 * hash) + getData().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.InstallSnapshotRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.InstallSnapshotRequest) ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_InstallSnapshotRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_InstallSnapshotRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.class, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); term_ = 0L; leaderName_ = ""; lastIndex_ = 0L; lastTerm_ = 0L; lastConfig_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000010); data_ = com.google.protobuf.ByteString.EMPTY; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_InstallSnapshotRequest_descriptor; } public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest build() { ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest buildPartial() { ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest result = new ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.term_ = term_; result.leaderName_ = leaderName_; result.lastIndex_ = lastIndex_; result.lastTerm_ = lastTerm_; if (((bitField0_ & 0x00000010) == 0x00000010)) { lastConfig_ = lastConfig_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000010); } result.lastConfig_ = lastConfig_; result.data_ = data_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest other) { if (other == ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest.getDefaultInstance()) return this; if (other.getTerm() != 0L) { setTerm(other.getTerm()); } if (!other.getLeaderName().isEmpty()) { leaderName_ = other.leaderName_; onChanged(); } if (other.getLastIndex() != 0L) { setLastIndex(other.getLastIndex()); } if (other.getLastTerm() != 0L) { setLastTerm(other.getLastTerm()); } if (!other.lastConfig_.isEmpty()) { if (lastConfig_.isEmpty()) { lastConfig_ = other.lastConfig_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureLastConfigIsMutable(); lastConfig_.addAll(other.lastConfig_); } onChanged(); } if (other.getData() != com.google.protobuf.ByteString.EMPTY) { setData(other.getData()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long term_ ; /** * <pre> * Leader's term * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } /** * <pre> * Leader's term * </pre> * * <code>uint64 term = 1;</code> */ public Builder setTerm(long value) { term_ = value; onChanged(); return this; } /** * <pre> * Leader's term * </pre> * * <code>uint64 term = 1;</code> */ public Builder clearTerm() { term_ = 0L; onChanged(); return this; } private java.lang.Object leaderName_ = ""; /** * <pre> * So the follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public java.lang.String getLeaderName() { java.lang.Object ref = leaderName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); leaderName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * So the follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public com.google.protobuf.ByteString getLeaderNameBytes() { java.lang.Object ref = leaderName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); leaderName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * So the follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public Builder setLeaderName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } leaderName_ = value; onChanged(); return this; } /** * <pre> * So the follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public Builder clearLeaderName() { leaderName_ = getDefaultInstance().getLeaderName(); onChanged(); return this; } /** * <pre> * So the follower can redirect clients * </pre> * * <code>string leaderName = 2;</code> */ public Builder setLeaderNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); leaderName_ = value; onChanged(); return this; } private long lastIndex_ ; /** * <pre> * The snapshot replaces all entries up through and including this index * </pre> * * <code>uint64 lastIndex = 3;</code> */ public long getLastIndex() { return lastIndex_; } /** * <pre> * The snapshot replaces all entries up through and including this index * </pre> * * <code>uint64 lastIndex = 3;</code> */ public Builder setLastIndex(long value) { lastIndex_ = value; onChanged(); return this; } /** * <pre> * The snapshot replaces all entries up through and including this index * </pre> * * <code>uint64 lastIndex = 3;</code> */ public Builder clearLastIndex() { lastIndex_ = 0L; onChanged(); return this; } private long lastTerm_ ; /** * <pre> * The term of lastIndex * </pre> * * <code>uint64 lastTerm = 4;</code> */ public long getLastTerm() { return lastTerm_; } /** * <pre> * The term of lastIndex * </pre> * * <code>uint64 lastTerm = 4;</code> */ public Builder setLastTerm(long value) { lastTerm_ = value; onChanged(); return this; } /** * <pre> * The term of lastIndex * </pre> * * <code>uint64 lastTerm = 4;</code> */ public Builder clearLastTerm() { lastTerm_ = 0L; onChanged(); return this; } private com.google.protobuf.LazyStringList lastConfig_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureLastConfigIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { lastConfig_ = new com.google.protobuf.LazyStringArrayList(lastConfig_); bitField0_ |= 0x00000010; } } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public com.google.protobuf.ProtocolStringList getLastConfigList() { return lastConfig_.getUnmodifiableView(); } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public int getLastConfigCount() { return lastConfig_.size(); } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public java.lang.String getLastConfig(int index) { return lastConfig_.get(index); } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public com.google.protobuf.ByteString getLastConfigBytes(int index) { return lastConfig_.getByteString(index); } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public Builder setLastConfig( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureLastConfigIsMutable(); lastConfig_.set(index, value); onChanged(); return this; } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public Builder addLastConfig( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureLastConfigIsMutable(); lastConfig_.add(value); onChanged(); return this; } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public Builder addAllLastConfig( java.lang.Iterable<java.lang.String> values) { ensureLastConfigIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, lastConfig_); onChanged(); return this; } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public Builder clearLastConfig() { lastConfig_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** * <pre> * The latest cluster configuration as of lastIndex (included only with the first chunk) * </pre> * * <code>repeated string lastConfig = 5;</code> */ public Builder addLastConfigBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureLastConfigIsMutable(); lastConfig_.add(value); onChanged(); return this; } private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; /** * <pre> * raw bytes of the snapshot * </pre> * * <code>bytes data = 6;</code> */ public com.google.protobuf.ByteString getData() { return data_; } /** * <pre> * raw bytes of the snapshot * </pre> * * <code>bytes data = 6;</code> */ public Builder setData(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } data_ = value; onChanged(); return this; } /** * <pre> * raw bytes of the snapshot * </pre> * * <code>bytes data = 6;</code> */ public Builder clearData() { data_ = getDefaultInstance().getData(); onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.InstallSnapshotRequest) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.InstallSnapshotRequest) private static final ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest(); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<InstallSnapshotRequest> PARSER = new com.google.protobuf.AbstractParser<InstallSnapshotRequest>() { public InstallSnapshotRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new InstallSnapshotRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<InstallSnapshotRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<InstallSnapshotRequest> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface InstallSnapshotReplyOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.InstallSnapshotReply) com.google.protobuf.MessageOrBuilder { /** * <pre> * currentTerm, for the leader to update itself * </pre> * * <code>uint64 term = 1;</code> */ long getTerm(); /** * <pre> * index of candidate's last log entry * </pre> * * <code>uint64 nextIndex = 2;</code> */ long getNextIndex(); /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ java.lang.String getFollowerName(); /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ com.google.protobuf.ByteString getFollowerNameBytes(); } /** * Protobuf type {@code ai.eloquent.raft.InstallSnapshotReply} */ public static final class InstallSnapshotReply extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.InstallSnapshotReply) InstallSnapshotReplyOrBuilder { private static final long serialVersionUID = 0L; // Use InstallSnapshotReply.newBuilder() to construct. private InstallSnapshotReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private InstallSnapshotReply() { term_ = 0L; nextIndex_ = 0L; followerName_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private InstallSnapshotReply( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { term_ = input.readUInt64(); break; } case 16: { nextIndex_ = input.readUInt64(); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); followerName_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_InstallSnapshotReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_InstallSnapshotReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.class, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.Builder.class); } public static final int TERM_FIELD_NUMBER = 1; private long term_; /** * <pre> * currentTerm, for the leader to update itself * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } public static final int NEXTINDEX_FIELD_NUMBER = 2; private long nextIndex_; /** * <pre> * index of candidate's last log entry * </pre> * * <code>uint64 nextIndex = 2;</code> */ public long getNextIndex() { return nextIndex_; } public static final int FOLLOWERNAME_FIELD_NUMBER = 3; private volatile java.lang.Object followerName_; /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public java.lang.String getFollowerName() { java.lang.Object ref = followerName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); followerName_ = s; return s; } } /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public com.google.protobuf.ByteString getFollowerNameBytes() { java.lang.Object ref = followerName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); followerName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (term_ != 0L) { output.writeUInt64(1, term_); } if (nextIndex_ != 0L) { output.writeUInt64(2, nextIndex_); } if (!getFollowerNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, followerName_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (term_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, term_); } if (nextIndex_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(2, nextIndex_); } if (!getFollowerNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, followerName_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply other = (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) obj; boolean result = true; result = result && (getTerm() == other.getTerm()); result = result && (getNextIndex() == other.getNextIndex()); result = result && getFollowerName() .equals(other.getFollowerName()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TERM_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTerm()); hash = (37 * hash) + NEXTINDEX_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getNextIndex()); hash = (37 * hash) + FOLLOWERNAME_FIELD_NUMBER; hash = (53 * hash) + getFollowerName().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.InstallSnapshotReply} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.InstallSnapshotReply) ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReplyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_InstallSnapshotReply_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_InstallSnapshotReply_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.class, ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); term_ = 0L; nextIndex_ = 0L; followerName_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_InstallSnapshotReply_descriptor; } public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply build() { ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply buildPartial() { ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply result = new ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply(this); result.term_ = term_; result.nextIndex_ = nextIndex_; result.followerName_ = followerName_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply other) { if (other == ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply.getDefaultInstance()) return this; if (other.getTerm() != 0L) { setTerm(other.getTerm()); } if (other.getNextIndex() != 0L) { setNextIndex(other.getNextIndex()); } if (!other.getFollowerName().isEmpty()) { followerName_ = other.followerName_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private long term_ ; /** * <pre> * currentTerm, for the leader to update itself * </pre> * * <code>uint64 term = 1;</code> */ public long getTerm() { return term_; } /** * <pre> * currentTerm, for the leader to update itself * </pre> * * <code>uint64 term = 1;</code> */ public Builder setTerm(long value) { term_ = value; onChanged(); return this; } /** * <pre> * currentTerm, for the leader to update itself * </pre> * * <code>uint64 term = 1;</code> */ public Builder clearTerm() { term_ = 0L; onChanged(); return this; } private long nextIndex_ ; /** * <pre> * index of candidate's last log entry * </pre> * * <code>uint64 nextIndex = 2;</code> */ public long getNextIndex() { return nextIndex_; } /** * <pre> * index of candidate's last log entry * </pre> * * <code>uint64 nextIndex = 2;</code> */ public Builder setNextIndex(long value) { nextIndex_ = value; onChanged(); return this; } /** * <pre> * index of candidate's last log entry * </pre> * * <code>uint64 nextIndex = 2;</code> */ public Builder clearNextIndex() { nextIndex_ = 0L; onChanged(); return this; } private java.lang.Object followerName_ = ""; /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public java.lang.String getFollowerName() { java.lang.Object ref = followerName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); followerName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public com.google.protobuf.ByteString getFollowerNameBytes() { java.lang.Object ref = followerName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); followerName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public Builder setFollowerName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } followerName_ = value; onChanged(); return this; } /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public Builder clearFollowerName() { followerName_ = getDefaultInstance().getFollowerName(); onChanged(); return this; } /** * <pre> * The name of the follower that sent this reply. *&#47; * </pre> * * <code>string followerName = 3;</code> */ public Builder setFollowerNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); followerName_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.InstallSnapshotReply) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.InstallSnapshotReply) private static final ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply(); } public static ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<InstallSnapshotReply> PARSER = new com.google.protobuf.AbstractParser<InstallSnapshotReply>() { public InstallSnapshotReply parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new InstallSnapshotReply(input, extensionRegistry); } }; public static com.google.protobuf.Parser<InstallSnapshotReply> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<InstallSnapshotReply> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.InstallSnapshotReply getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface StateMachineOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.StateMachine) com.google.protobuf.MessageOrBuilder { /** * <pre> * the actual implementation of the state machine -- implementation specific so we save it as bytes * </pre> * * <code>bytes payload = 1;</code> */ com.google.protobuf.ByteString getPayload(); /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ java.util.List<java.lang.String> getHospiceList(); /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ int getHospiceCount(); /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ java.lang.String getHospice(int index); /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ com.google.protobuf.ByteString getHospiceBytes(int index); } /** * Protobuf type {@code ai.eloquent.raft.StateMachine} */ public static final class StateMachine extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.StateMachine) StateMachineOrBuilder { private static final long serialVersionUID = 0L; // Use StateMachine.newBuilder() to construct. private StateMachine(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private StateMachine() { payload_ = com.google.protobuf.ByteString.EMPTY; hospice_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private StateMachine( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { payload_ = input.readBytes(); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { hospice_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000002; } hospice_.add(s); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { hospice_ = hospice_.getUnmodifiableView(); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_StateMachine_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_StateMachine_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.StateMachine.class, ai.eloquent.raft.EloquentRaftProto.StateMachine.Builder.class); } private int bitField0_; public static final int PAYLOAD_FIELD_NUMBER = 1; private com.google.protobuf.ByteString payload_; /** * <pre> * the actual implementation of the state machine -- implementation specific so we save it as bytes * </pre> * * <code>bytes payload = 1;</code> */ public com.google.protobuf.ByteString getPayload() { return payload_; } public static final int HOSPICE_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList hospice_; /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public com.google.protobuf.ProtocolStringList getHospiceList() { return hospice_; } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public int getHospiceCount() { return hospice_.size(); } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public java.lang.String getHospice(int index) { return hospice_.get(index); } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public com.google.protobuf.ByteString getHospiceBytes(int index) { return hospice_.getByteString(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!payload_.isEmpty()) { output.writeBytes(1, payload_); } for (int i = 0; i < hospice_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, hospice_.getRaw(i)); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!payload_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, payload_); } { int dataSize = 0; for (int i = 0; i < hospice_.size(); i++) { dataSize += computeStringSizeNoTag(hospice_.getRaw(i)); } size += dataSize; size += 1 * getHospiceList().size(); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.EloquentRaftProto.StateMachine)) { return super.equals(obj); } ai.eloquent.raft.EloquentRaftProto.StateMachine other = (ai.eloquent.raft.EloquentRaftProto.StateMachine) obj; boolean result = true; result = result && getPayload() .equals(other.getPayload()); result = result && getHospiceList() .equals(other.getHospiceList()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PAYLOAD_FIELD_NUMBER; hash = (53 * hash) + getPayload().hashCode(); if (getHospiceCount() > 0) { hash = (37 * hash) + HOSPICE_FIELD_NUMBER; hash = (53 * hash) + getHospiceList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.EloquentRaftProto.StateMachine prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.StateMachine} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.StateMachine) ai.eloquent.raft.EloquentRaftProto.StateMachineOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_StateMachine_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_StateMachine_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.EloquentRaftProto.StateMachine.class, ai.eloquent.raft.EloquentRaftProto.StateMachine.Builder.class); } // Construct using ai.eloquent.raft.EloquentRaftProto.StateMachine.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); payload_ = com.google.protobuf.ByteString.EMPTY; hospice_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.EloquentRaftProto.internal_static_ai_eloquent_raft_StateMachine_descriptor; } public ai.eloquent.raft.EloquentRaftProto.StateMachine getDefaultInstanceForType() { return ai.eloquent.raft.EloquentRaftProto.StateMachine.getDefaultInstance(); } public ai.eloquent.raft.EloquentRaftProto.StateMachine build() { ai.eloquent.raft.EloquentRaftProto.StateMachine result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.EloquentRaftProto.StateMachine buildPartial() { ai.eloquent.raft.EloquentRaftProto.StateMachine result = new ai.eloquent.raft.EloquentRaftProto.StateMachine(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.payload_ = payload_; if (((bitField0_ & 0x00000002) == 0x00000002)) { hospice_ = hospice_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000002); } result.hospice_ = hospice_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.EloquentRaftProto.StateMachine) { return mergeFrom((ai.eloquent.raft.EloquentRaftProto.StateMachine)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.EloquentRaftProto.StateMachine other) { if (other == ai.eloquent.raft.EloquentRaftProto.StateMachine.getDefaultInstance()) return this; if (other.getPayload() != com.google.protobuf.ByteString.EMPTY) { setPayload(other.getPayload()); } if (!other.hospice_.isEmpty()) { if (hospice_.isEmpty()) { hospice_ = other.hospice_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureHospiceIsMutable(); hospice_.addAll(other.hospice_); } onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.EloquentRaftProto.StateMachine parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.EloquentRaftProto.StateMachine) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private com.google.protobuf.ByteString payload_ = com.google.protobuf.ByteString.EMPTY; /** * <pre> * the actual implementation of the state machine -- implementation specific so we save it as bytes * </pre> * * <code>bytes payload = 1;</code> */ public com.google.protobuf.ByteString getPayload() { return payload_; } /** * <pre> * the actual implementation of the state machine -- implementation specific so we save it as bytes * </pre> * * <code>bytes payload = 1;</code> */ public Builder setPayload(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } payload_ = value; onChanged(); return this; } /** * <pre> * the actual implementation of the state machine -- implementation specific so we save it as bytes * </pre> * * <code>bytes payload = 1;</code> */ public Builder clearPayload() { payload_ = getDefaultInstance().getPayload(); onChanged(); return this; } private com.google.protobuf.LazyStringList hospice_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureHospiceIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { hospice_ = new com.google.protobuf.LazyStringArrayList(hospice_); bitField0_ |= 0x00000002; } } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public com.google.protobuf.ProtocolStringList getHospiceList() { return hospice_.getUnmodifiableView(); } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public int getHospiceCount() { return hospice_.size(); } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public java.lang.String getHospice(int index) { return hospice_.get(index); } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public com.google.protobuf.ByteString getHospiceBytes(int index) { return hospice_.getByteString(index); } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public Builder setHospice( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureHospiceIsMutable(); hospice_.set(index, value); onChanged(); return this; } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public Builder addHospice( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureHospiceIsMutable(); hospice_.add(value); onChanged(); return this; } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public Builder addAllHospice( java.lang.Iterable<java.lang.String> values) { ensureHospiceIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, hospice_); onChanged(); return this; } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public Builder clearHospice() { hospice_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * The list of nodes in the hospice * </pre> * * <code>repeated string hospice = 2;</code> */ public Builder addHospiceBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureHospiceIsMutable(); hospice_.add(value); onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.StateMachine) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.StateMachine) private static final ai.eloquent.raft.EloquentRaftProto.StateMachine DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.EloquentRaftProto.StateMachine(); } public static ai.eloquent.raft.EloquentRaftProto.StateMachine getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<StateMachine> PARSER = new com.google.protobuf.AbstractParser<StateMachine>() { public StateMachine parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new StateMachine(input, extensionRegistry); } }; public static com.google.protobuf.Parser<StateMachine> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<StateMachine> getParserForType() { return PARSER; } public ai.eloquent.raft.EloquentRaftProto.StateMachine getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_RaftMessage_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_RaftMessage_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_AppendEntriesRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_AppendEntriesRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_AppendEntriesReply_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_AppendEntriesReply_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_RequestVoteRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_RequestVoteRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_RequestVoteReply_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_RequestVoteReply_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_ApplyTransitionRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_ApplyTransitionRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_ApplyTransitionReply_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_ApplyTransitionReply_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_LogEntry_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_LogEntry_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_AddServerRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_AddServerRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_AddServerReply_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_AddServerReply_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_RemoveServerRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_RemoveServerRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_RemoveServerReply_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_RemoveServerReply_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_LivenessCheckRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_LivenessCheckRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_LivenessCheckReply_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_LivenessCheckReply_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_InstallSnapshotRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_InstallSnapshotRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_InstallSnapshotReply_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_InstallSnapshotReply_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_StateMachine_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_StateMachine_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\022EloquentRaft.proto\022\020ai.eloquent.raft\"\314" + "\006\n\013RaftMessage\022\r\n\005isRPC\030\001 \001(\010\022?\n\rappendE" + "ntries\030\002 \001(\0132&.ai.eloquent.raft.AppendEn" + "triesRequestH\000\022<\n\014requestVotes\030\003 \001(\0132$.a" + "i.eloquent.raft.RequestVoteRequestH\000\022C\n\017" + "applyTransition\030\004 \001(\0132(.ai.eloquent.raft" + ".ApplyTransitionRequestH\000\0227\n\taddServer\030\005" + " \001(\0132\".ai.eloquent.raft.AddServerRequest" + "H\000\022=\n\014removeServer\030\006 \001(\0132%.ai.eloquent.r" + "aft.RemoveServerRequestH\000\022C\n\017installSnap" + "shot\030\007 \001(\0132(.ai.eloquent.raft.InstallSna" + "pshotRequestH\000\022B\n\022appendEntriesReply\030\010 \001" + "(\0132$.ai.eloquent.raft.AppendEntriesReply" + "H\000\022?\n\021requestVotesReply\030\t \001(\0132\".ai.eloqu" + "ent.raft.RequestVoteReplyH\000\022F\n\024applyTran" + "sitionReply\030\n \001(\0132&.ai.eloquent.raft.App" + "lyTransitionReplyH\000\022:\n\016addServerReply\030\013 " + "\001(\0132 .ai.eloquent.raft.AddServerReplyH\000\022" + "@\n\021removeServerReply\030\014 \001(\0132#.ai.eloquent" + ".raft.RemoveServerReplyH\000\022F\n\024installSnap" + "shotReply\030\r \001(\0132&.ai.eloquent.raft.Insta" + "llSnapshotReplyH\000\022\016\n\006sender\030\016 \001(\tB\n\n\010con" + "tents\"\274\001\n\024AppendEntriesRequest\022\014\n\004term\030\001" + " \001(\004\022\022\n\nleaderName\030\002 \001(\t\022\024\n\014prevLogIndex" + "\030\003 \001(\004\022\023\n\013prevLogTerm\030\004 \001(\004\022+\n\007entries\030\005" + " \003(\0132\032.ai.eloquent.raft.LogEntry\022\024\n\014lead" + "erCommit\030\006 \001(\004\022\024\n\014leaderTimish\030\007 \001(\004\"w\n\022" + "AppendEntriesReply\022\014\n\004term\030\001 \001(\004\022\017\n\007succ" + "ess\030\002 \001(\010\022\021\n\tnextIndex\030\003 \001(\004\022\024\n\014follower" + "Name\030\004 \001(\t\022\031\n\021missingFromQuorum\030\005 \001(\010\"d\n" + "\022RequestVoteRequest\022\014\n\004term\030\001 \001(\004\022\025\n\rcan" + "didateName\030\002 \001(\t\022\024\n\014lastLogIndex\030\003 \001(\004\022\023" + "\n\013lastLogTerm\030\004 \001(\004\"a\n\020RequestVoteReply\022" + "\014\n\004term\030\001 \001(\004\022\024\n\014followerTerm\030\004 \001(\004\022\023\n\013v" + "oteGranted\030\002 \001(\010\022\024\n\014followerName\030\003 \001(\t\"z" + "\n\026ApplyTransitionRequest\022\014\n\004term\030\001 \001(\004\022\024" + "\n\ntransition\030\002 \001(\014H\000\022\034\n\022new_hospice_memb" + "er\030\004 \001(\tH\000\022\023\n\013forwardedBy\030\003 \003(\tB\t\n\007paylo" + "ad\"b\n\024ApplyTransitionReply\022\014\n\004term\030\001 \001(\004" + "\022\017\n\007success\030\002 \001(\010\022\025\n\rnewEntryIndex\030\003 \001(\004" + "\022\024\n\014newEntryTerm\030\004 \001(\004\"\253\001\n\010LogEntry\022\r\n\005i" + "ndex\030\001 \001(\004\022\014\n\004term\030\002 \001(\004\022,\n\004type\030\003 \001(\0162\036" + ".ai.eloquent.raft.LogEntryType\022\024\n\ntransi" + "tion\030\004 \001(\014H\000\022\034\n\022new_hospice_member\030\006 \001(\t" + "H\000\022\025\n\rconfiguration\030\005 \003(\tB\t\n\007payload\"J\n\020" + "AddServerRequest\022\021\n\tnewServer\030\001 \001(\t\022\016\n\006q" + "uorum\030\002 \003(\t\022\023\n\013forwardedBy\030\003 \003(\t\"b\n\016AddS" + "erverReply\0228\n\006status\030\001 \001(\0162(.ai.eloquent" + ".raft.MembershipChangeStatus\022\026\n\016leadersh" + "ipHint\030\002 \001(\t\"M\n\023RemoveServerRequest\022\021\n\to" + "ldServer\030\001 \001(\t\022\016\n\006quorum\030\002 \003(\t\022\023\n\013forwar" + "dedBy\030\003 \003(\t\"e\n\021RemoveServerReply\0228\n\006stat" + "us\030\001 \001(\0162(.ai.eloquent.raft.MembershipCh" + "angeStatus\022\026\n\016leadershipHint\030\002 \001(\t\"\026\n\024Li" + "venessCheckRequest\"\"\n\022LivenessCheckReply" + "\022\014\n\004live\030\001 \001(\010\"\201\001\n\026InstallSnapshotReques" + "t\022\014\n\004term\030\001 \001(\004\022\022\n\nleaderName\030\002 \001(\t\022\021\n\tl" + "astIndex\030\003 \001(\004\022\020\n\010lastTerm\030\004 \001(\004\022\022\n\nlast" + "Config\030\005 \003(\t\022\014\n\004data\030\006 \001(\014\"M\n\024InstallSna" + "pshotReply\022\014\n\004term\030\001 \001(\004\022\021\n\tnextIndex\030\002 " + "\001(\004\022\024\n\014followerName\030\003 \001(\t\"0\n\014StateMachin" + "e\022\017\n\007payload\030\001 \001(\014\022\017\n\007hospice\030\002 \003(\t*1\n\014L" + "ogEntryType\022\016\n\nTRANSITION\020\000\022\021\n\rCONFIGURA" + "TION\020\001*N\n\026MembershipChangeStatus\022\006\n\002OK\020\000" + "\022\013\n\007TIMEOUT\020\001\022\016\n\nNOT_LEADER\020\002\022\017\n\013OTHER_E" + "RROR\020\0032K\n\004Raft\022C\n\003rpc\022\035.ai.eloquent.raft" + ".RaftMessage\032\035.ai.eloquent.raft.RaftMess" + "ageB%\n\020ai.eloquent.raftB\021EloquentRaftPro" + "tob\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_ai_eloquent_raft_RaftMessage_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_ai_eloquent_raft_RaftMessage_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_RaftMessage_descriptor, new java.lang.String[] { "IsRPC", "AppendEntries", "RequestVotes", "ApplyTransition", "AddServer", "RemoveServer", "InstallSnapshot", "AppendEntriesReply", "RequestVotesReply", "ApplyTransitionReply", "AddServerReply", "RemoveServerReply", "InstallSnapshotReply", "Sender", "Contents", }); internal_static_ai_eloquent_raft_AppendEntriesRequest_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_ai_eloquent_raft_AppendEntriesRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_AppendEntriesRequest_descriptor, new java.lang.String[] { "Term", "LeaderName", "PrevLogIndex", "PrevLogTerm", "Entries", "LeaderCommit", "LeaderTimish", }); internal_static_ai_eloquent_raft_AppendEntriesReply_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_ai_eloquent_raft_AppendEntriesReply_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_AppendEntriesReply_descriptor, new java.lang.String[] { "Term", "Success", "NextIndex", "FollowerName", "MissingFromQuorum", }); internal_static_ai_eloquent_raft_RequestVoteRequest_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_ai_eloquent_raft_RequestVoteRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_RequestVoteRequest_descriptor, new java.lang.String[] { "Term", "CandidateName", "LastLogIndex", "LastLogTerm", }); internal_static_ai_eloquent_raft_RequestVoteReply_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_ai_eloquent_raft_RequestVoteReply_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_RequestVoteReply_descriptor, new java.lang.String[] { "Term", "FollowerTerm", "VoteGranted", "FollowerName", }); internal_static_ai_eloquent_raft_ApplyTransitionRequest_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_ai_eloquent_raft_ApplyTransitionRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_ApplyTransitionRequest_descriptor, new java.lang.String[] { "Term", "Transition", "NewHospiceMember", "ForwardedBy", "Payload", }); internal_static_ai_eloquent_raft_ApplyTransitionReply_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_ai_eloquent_raft_ApplyTransitionReply_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_ApplyTransitionReply_descriptor, new java.lang.String[] { "Term", "Success", "NewEntryIndex", "NewEntryTerm", }); internal_static_ai_eloquent_raft_LogEntry_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_ai_eloquent_raft_LogEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_LogEntry_descriptor, new java.lang.String[] { "Index", "Term", "Type", "Transition", "NewHospiceMember", "Configuration", "Payload", }); internal_static_ai_eloquent_raft_AddServerRequest_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_ai_eloquent_raft_AddServerRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_AddServerRequest_descriptor, new java.lang.String[] { "NewServer", "Quorum", "ForwardedBy", }); internal_static_ai_eloquent_raft_AddServerReply_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_ai_eloquent_raft_AddServerReply_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_AddServerReply_descriptor, new java.lang.String[] { "Status", "LeadershipHint", }); internal_static_ai_eloquent_raft_RemoveServerRequest_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_ai_eloquent_raft_RemoveServerRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_RemoveServerRequest_descriptor, new java.lang.String[] { "OldServer", "Quorum", "ForwardedBy", }); internal_static_ai_eloquent_raft_RemoveServerReply_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_ai_eloquent_raft_RemoveServerReply_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_RemoveServerReply_descriptor, new java.lang.String[] { "Status", "LeadershipHint", }); internal_static_ai_eloquent_raft_LivenessCheckRequest_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_ai_eloquent_raft_LivenessCheckRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_LivenessCheckRequest_descriptor, new java.lang.String[] { }); internal_static_ai_eloquent_raft_LivenessCheckReply_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_ai_eloquent_raft_LivenessCheckReply_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_LivenessCheckReply_descriptor, new java.lang.String[] { "Live", }); internal_static_ai_eloquent_raft_InstallSnapshotRequest_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_ai_eloquent_raft_InstallSnapshotRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_InstallSnapshotRequest_descriptor, new java.lang.String[] { "Term", "LeaderName", "LastIndex", "LastTerm", "LastConfig", "Data", }); internal_static_ai_eloquent_raft_InstallSnapshotReply_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_ai_eloquent_raft_InstallSnapshotReply_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_InstallSnapshotReply_descriptor, new java.lang.String[] { "Term", "NextIndex", "FollowerName", }); internal_static_ai_eloquent_raft_StateMachine_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_ai_eloquent_raft_StateMachine_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_StateMachine_descriptor, new java.lang.String[] { "Payload", "Hospice", }); } // @@protoc_insertion_point(outer_class_scope) }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/InstantTransport.java
package ai.eloquent.raft; import ai.eloquent.util.SafeTimerTask; import ai.eloquent.util.Span; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import java.util.function.Function; /** * This is used for benchmarking, and to do JIT burn-ins for latency sensitive code paths. */ public class InstantTransport implements RaftTransport { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(InstantTransport.class); Map<String, RaftAlgorithm> bound = new HashMap<>(); @Override public void bind(RaftAlgorithm listener) { bound.put(listener.serverName(), listener); } @Override public Collection<RaftAlgorithm> boundAlgorithms() { return bound.values(); } @Override public void rpcTransport(String sender, String destination, EloquentRaftProto.RaftMessage message, Consumer<EloquentRaftProto.RaftMessage> onResponseReceived, Runnable onTimeout, long timeout) { try { EloquentRaftProto.RaftMessage reply = bound.get(destination).receiveRPC(message, System.currentTimeMillis()).get(); onResponseReceived.accept(reply); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } @Override public void sendTransport(String sender, String destination, EloquentRaftProto.RaftMessage message) { bound.get(destination).receiveMessage(message, (reply) -> { sendTransport(destination, sender, reply); }, System.currentTimeMillis()); } @Override public void broadcastTransport(String sender, EloquentRaftProto.RaftMessage message) { for (RaftAlgorithm algorithm : bound.values()) { if (!algorithm.serverName().equals(sender)) { try { EloquentRaftProto.RaftMessage reply = algorithm.receiveRPC(message, System.currentTimeMillis()).get(); sendTransport(algorithm.serverName(), sender, reply); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } } @Override public Span expectedNetworkDelay() { return new Span(0,1); } /** Schedule an event every |period| seconds. This is an alias for {@link ai.eloquent.util.SafeTimer#scheduleAtFixedRate(SafeTimerTask, long, long)}, but mockable */ @Override public void scheduleAtFixedRate(SafeTimerTask timerTask, long period) { // ignore } /** Schedule an event every |period| seconds. This is an alias for {@link ai.eloquent.util.SafeTimer#schedule(SafeTimerTask, long)}, but mockable */ @Override public void schedule(SafeTimerTask timerTask, long delay) { // ignore } private static class AddOne implements Function<byte[], byte[]> { @Override public byte[] apply(byte[] oldBytes) { int value = ByteBuffer.wrap(oldBytes).getInt() + 1; return ByteBuffer.allocate(4).putInt(value).array(); } } /** * This runs a batch of burn-in requests * * @param L node to burn in on * @param numIterations the number of iterations to run */ private static double burnInRun(Theseus L, long numIterations) { long startTime = System.nanoTime(); for (int i = 0; i < numIterations; i++) { try { L.withElementAsync("key_"+(i % 50), new AddOne(), () -> ByteBuffer.allocate(4).putInt(0).array(), true).get(5, TimeUnit.SECONDS); L.node.algorithm.heartbeat(i); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.warn("Caught exception running JIT burn in:", e); } /* L.node.algorithm.receiveApplyTransitionRPC(EloquentRaftProto.ApplyTransitionRequest.newBuilder() .setTerm(0) .setTransition(ByteString.copyFrom(KeyValueStateMachine.createSetValueTransition("key_"+(i % 50), new byte[]{10}))) .build(), i * 1000); */ } return (double)(System.nanoTime() - startTime) / numIterations; } /** * We use this to burn in the important routines in Raft */ public static void burnInJIT() { log.info("Ignoring the burn in run on Raft, since the InstantTransport deadlocks..."); /* log.info("Setting up to burn in the JIT on Raft"); int oldLogLevel = EloquentLogger.level(); EloquentLogger.setLevel(2); // the normal level for logs, so we don't print trace logs during burn-in InstantTransport transport = new InstantTransport(); RaftLifecycle lifecycle = RaftLifecycle.newBuilder().mockTime().build(); Theseus L = new Theseus(new SingleThreadedRaftAlgorithm(new EloquentRaftAlgorithm("L", new KeyValueStateMachine("L"), transport, 3, MoreExecutors.newDirectExecutorService(), Optional.of(lifecycle)), MoreExecutors.newDirectExecutorService()), transport, lifecycle); Theseus A = new Theseus(new SingleThreadedRaftAlgorithm(new EloquentRaftAlgorithm("A", new KeyValueStateMachine("A"), transport, 3, MoreExecutors.newDirectExecutorService(), Optional.of(lifecycle)), MoreExecutors.newDirectExecutorService()), transport, lifecycle); Theseus B = new Theseus(new SingleThreadedRaftAlgorithm(new EloquentRaftAlgorithm("B", new KeyValueStateMachine("B"), transport, 3, MoreExecutors.newDirectExecutorService(), Optional.of(lifecycle)), MoreExecutors.newDirectExecutorService()), transport, lifecycle); L.start(); A.start(); B.start(); L.bootstrap(false); L.node.algorithm.triggerElection(0); L.node.algorithm.heartbeat(100); L.node.algorithm.mutableState().log.latestQuorumMembers.add("A"); L.node.algorithm.mutableState().log.latestQuorumMembers.add("B"); A.node.algorithm.mutableState().log.latestQuorumMembers.add("L"); A.node.algorithm.mutableState().log.latestQuorumMembers.add("B"); B.node.algorithm.mutableState().log.latestQuorumMembers.add("L"); B.node.algorithm.mutableState().log.latestQuorumMembers.add("A"); // Do a first pass to calibrate initial speed log.info("Burning in JIT (This takes a few seconds) ..."); double initialSpeed = burnInRun(L, 10L); // Do a big run to burn in the JIT burnInRun(L, 50000L); // Do another pass to figure out improvement in speed double jitSpeed = burnInRun(L, 10L); log.info("JIT results:\nInitial speed: "+initialSpeed+" nanosec compute / commit\nJIT speed: "+jitSpeed+" nanosec compute / commit\nImprovement: "+(initialSpeed * 100 / jitSpeed)+"%"); lifecycle.shutdown(true); L.close(); A.close(); B.close(); log.info("Done burning in JIT..."); EloquentLogger.setLevel(oldLogLevel); */ } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/KeyValueStateMachine.java
package ai.eloquent.raft; import ai.eloquent.error.RaftErrorListener; import ai.eloquent.monitoring.Prometheus; import ai.eloquent.util.IdentityHashSet; import ai.eloquent.util.StackTrace; import ai.eloquent.util.SystemUtils; import ai.eloquent.util.TimerUtils; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.annotation.Nonnull; import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; /** * This is the standard state machine we use to implement our RAFT distributed storage. It has two maps: * * - string to lock (for distributed locking) * - string to byte[] (for distributed state) * * The state machine implements locks as queues. All changes can be listened for with custom listeners on the state * machine. */ public class KeyValueStateMachine extends RaftStateMachine { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(KeyValueStateMachine.class); /** The number of elements currently in the queue. */ private static final Object gaugeNumListeners = Prometheus.gaugeBuild("kv_state_machine_listeners", "The number of listeners on Raft's Key/Value state machine"); /** Keeps track of existing {@link RaftErrorListener} **/ private static ArrayList<RaftErrorListener> errorListeners = new ArrayList<>(); /** * Keeps track of an additional {@link RaftErrorListener} in this class * * @param errorListener The error listener to add. */ protected void addErrorListener(RaftErrorListener errorListener) { errorListeners.add(errorListener); } /** * Stop listening from a specific {@link RaftErrorListener} * @param errorListener The error listener to be removed */ protected void removeErrorListener(RaftErrorListener errorListener) { errorListeners.remove(errorListener); } /** * Clears all the {@link RaftErrorListener}s attached to this class. */ protected void clearErrorListeners() { errorListeners.clear(); } /** * Alert each of the {@link RaftErrorListener}s attached to this class. */ protected void throwRaftError(String incidentKey, String debugMessage) { errorListeners.forEach(listener -> listener.accept(incidentKey, debugMessage, Thread.currentThread().getStackTrace())); } static { new KeyValueStateMachine("name").serialize(); // warm up the proto class loaders } /** * This holds a locally registered callback that will be called whenever the state machine changes. This lets code * wait for changes to the cluster, and respond appropriately. */ @FunctionalInterface public interface ChangeListener { /** * Run on a value of the state machine changing. * * @param changedKey The key that changed. * @param newValue The new value of the changed key, or {@link Optional#empty()} if we are removing a key. * @param state The new complete state of the state machine. */ void onChange(String changedKey, Optional<byte[]> newValue, Map<String, byte[]> state); } /** * This holds a value with an optional owner, so that it can be cleaned up automatically when the owner disconnects. */ static class ValueWithOptionalOwner { /** * The raw value on this Value object. */ final byte[] value; /** * The optional owner of this value. This is the {@link RaftState#serverName} of the owner. */ final Optional<String> owner; /** * The last time this element was accessed, as a millisecond value since the epoch. */ long lastAccessed; /** * The timestamp this object was created, as a millisecond since the epock. */ final long createdAt; /** Create a value without an owner. */ public ValueWithOptionalOwner(byte[] value, long now) { this(value, null, now); } /** Create a value with an owner. */ public ValueWithOptionalOwner(byte[] value, String owner, long now) { this(value, owner, now, now); } /** The straightforward constructor. */ private ValueWithOptionalOwner(byte[] value, String owner, long now, long createdAt) { this.value = value; this.owner = Optional.ofNullable(owner); this.lastAccessed = now; this.createdAt = createdAt; } /** * Get the value of the state machine, but also register the time at which we got it */ public byte[] registerGet(long now) { this.lastAccessed = now; return value; } /** * Write this value as a proto object that can be sent on the wire in, e.g., a snapshot. */ public KeyValueStateMachineProto.ValueWithOptionalOwner serialize() { KeyValueStateMachineProto.ValueWithOptionalOwner.Builder builder = KeyValueStateMachineProto.ValueWithOptionalOwner.newBuilder(); owner.ifPresent(builder::setOwner); return builder .setValue(ByteString.copyFrom(value)) .setLastAccessed(this.lastAccessed) .setCreatedAt(this.createdAt) .build() ; } /** * Read this value from a serialized value -- e.g., reading from a snapshot. */ public static ValueWithOptionalOwner deserialize(KeyValueStateMachineProto.ValueWithOptionalOwner value) { return new ValueWithOptionalOwner( value.getValue().toByteArray(), "".equals(value.getOwner()) ? null : value.getOwner(), value.getLastAccessed(), value.getCreatedAt()); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ValueWithOptionalOwner that = (ValueWithOptionalOwner) o; return Arrays.equals(value, that.value) && owner.equals(that.owner); } /** {@inheritDoc} */ @Override public int hashCode() { int result = Arrays.hashCode(value); result = 31 * result + owner.hashCode(); return result; } } /** * This is the private implementation for a QueueLock. */ static class QueueLock { Optional<LockRequest> holder; List<LockRequest> waiting; public QueueLock(Optional<LockRequest> holder, List<LockRequest> waiting) { this.holder = holder; this.waiting = waiting; } public KeyValueStateMachineProto.QueueLock serialize() { KeyValueStateMachineProto.QueueLock.Builder builder = KeyValueStateMachineProto.QueueLock.newBuilder(); holder.ifPresent(h -> builder.setHolder(h.serialize())); builder.addAllWaiting(waiting.stream().map(LockRequest::serialize).collect(Collectors.toList())); return builder.build(); } public static QueueLock deserialize(KeyValueStateMachineProto.QueueLock queueLock) { Optional<LockRequest> holder; if (queueLock.hasHolder()) { holder = Optional.of(LockRequest.deserialize(queueLock.getHolder())); } else { holder = Optional.empty(); } List<LockRequest> waitingList = queueLock.getWaitingList().stream().map(LockRequest::deserialize).collect(Collectors.toList()); return new QueueLock(holder, waitingList); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QueueLock queueLock = (QueueLock) o; return Objects.equals(holder, queueLock.holder) && Objects.equals(waiting, queueLock.waiting); } @Override public int hashCode() { return Objects.hash(holder, waiting); } } /** * This is the private implementation for a LockRequest. */ static class LockRequest { String server; String uniqueHash; public LockRequest(String server, String uniqueHash) { this.server = server; this.uniqueHash = uniqueHash; } public KeyValueStateMachineProto.LockRequest serialize() { KeyValueStateMachineProto.LockRequest.Builder builder = KeyValueStateMachineProto.LockRequest.newBuilder(); builder.setServer(server); builder.setUniqueHash(uniqueHash); return builder.build(); } public static LockRequest deserialize(KeyValueStateMachineProto.LockRequest lockRequest) { return new LockRequest(lockRequest.getServer(), lockRequest.getUniqueHash()); } @Override public String toString() { return "LockRequest from "+server+" with "+uniqueHash; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LockRequest request = (LockRequest) o; return server.equals(request.server) && uniqueHash.equals(request.uniqueHash); } @Override public int hashCode() { int result = server.hashCode(); result = 31 * result + uniqueHash.hashCode(); return result; } } /** * This is how we track CompletableFutures that are waiting on a lock being acquired by a given requester. */ private static class LockAcquiredFuture { String lock; String requester; String uniqueHash; CompletableFuture<Boolean> future; public LockAcquiredFuture(String lock, String requester, String uniqueHash, CompletableFuture<Boolean> future) { this.lock = lock; this.requester = requester; this.uniqueHash = uniqueHash; this.future = future; } } private static class ValueWithOptionalOwnerMapView implements Map<String, byte[]> { final Map<String, ValueWithOptionalOwner> backingMap; public ValueWithOptionalOwnerMapView(Map<String, ValueWithOptionalOwner> backingMap) { this.backingMap = backingMap; } @Override public int size() { return this.backingMap.size(); } @Override public boolean isEmpty() { return this.backingMap.isEmpty(); } @Override public boolean containsKey(Object key) { return this.backingMap.containsKey(key); } @Override public boolean containsValue(Object value) { return this.backingMap.containsValue(value); } @Override public byte[] get(Object key) { return this.backingMap.get(key).value; } @Nullable @Override public byte[] put(String key, byte[] value) { throw new UnsupportedOperationException(); } @Override public byte[] remove(Object key) { throw new UnsupportedOperationException(); } @Override public void putAll(@Nonnull Map<? extends String, ? extends byte[]> m) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Nonnull @Override public Set<String> keySet() { return this.backingMap.keySet(); } @Nonnull @Override public Collection<byte[]> values() { return this.backingMap.values().stream().map(v -> v.value).collect(Collectors.toList()); } @Nonnull @Override public Set<Entry<String, byte[]>> entrySet() { return this.backingMap.entrySet().stream().map(e -> new Entry<String, byte[]>() { @Override public String getKey() { return e.getKey(); } @Override public byte[] getValue() { return e.getValue().value; } @Override public byte[] setValue(byte[] value) { throw new UnsupportedOperationException(); } }).collect(Collectors.toSet()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ValueWithOptionalOwnerMapView that = (ValueWithOptionalOwnerMapView) o; return Objects.equals(backingMap, that.backingMap); } @Override public int hashCode() { return Objects.hash(backingMap); } } /** * This is where we store our distributed state. */ final Map<String, ValueWithOptionalOwner> values = new ConcurrentHashMap<>(); /** * This is where we store out distributed locks */ final Map<String, QueueLock> locks = new ConcurrentHashMap<>(); /** * This is where we keep all the lock acquired futures that we need to check for */ final List<LockAcquiredFuture> lockAcquiredFutures = new ArrayList<>(); /** * This is where we keep all of the listeners that fire whenever the current state changes */ final Set<ChangeListener> changeListeners = new IdentityHashSet<>(); /** * A map from change listeners to their creation stack trace. */ Map<ChangeListener, StackTrace> changeListenerToTrace = new IdentityHashMap<>(); /** * The server that this state machine is running on. * @see RaftState#serverName */ public final Optional<String> serverName; /** Create a new state machine, with knowledge of what node it's running on */ public KeyValueStateMachine(String serverName) { this.serverName = Optional.ofNullable(serverName); } /** * This serializes the state machine's current state into a proto that can be read from {@link #overwriteWithSerialized(byte[], long, ExecutorService)}. * * @return a proto of this state machine */ @Override public synchronized ByteString serializeImpl() { long begin = System.currentTimeMillis(); try { KeyValueStateMachineProto.KVStateMachine.Builder builder = KeyValueStateMachineProto.KVStateMachine.newBuilder(); this.values.forEach((key, value) -> { builder.addValuesKeys(key); builder.addValuesValues(value.serialize()); }); this.locks.forEach((key, value) -> { builder.addLocksKeys(key); builder.addLocksValues(value.serialize()); }); return builder.build().toByteString(); } finally { if (!this.values.isEmpty() && System.currentTimeMillis() - begin > 10) { log.warn("Serialization of state machine took {}; {} entries and {} locks", TimerUtils.formatTimeSince(begin), this.values.size(), this.locks.size()); } } } /** * This overwrites the current state of the state machine with a serialized proto. All the current state of the state * machine is overwritten, and the new state is substituted in its place. * * @param serialized the state machine to overwrite this one with, in serialized form * @param now the current time, for mocking. */ @Override public synchronized void overwriteWithSerializedImpl(byte[] serialized, long now, ExecutorService pool) { try { KeyValueStateMachineProto.KVStateMachine serializedStateMachine = KeyValueStateMachineProto.KVStateMachine.parseFrom(serialized); this.values.clear(); for (int i = 0; i < serializedStateMachine.getValuesKeysCount(); ++i) { ValueWithOptionalOwner value = ValueWithOptionalOwner.deserialize(serializedStateMachine.getValuesValues(i)); this.values.put(serializedStateMachine.getValuesKeys(i), value); } this.locks.clear(); for (int i = 0; i < serializedStateMachine.getLocksKeysCount(); ++i) { this.locks.put(serializedStateMachine.getLocksKeys(i), QueueLock.deserialize(serializedStateMachine.getLocksValues(i))); } checkLocksAcquired(pool); } catch (InvalidProtocolBufferException e) { log.error("Attempting to deserialize an invalid snapshot! This is very bad. Leaving current state unchanged.", e); } } /** * This is responsible for applying a transition to the state machine. The transition is assumed to be coming in a * proto, and so is serialized as a byte array. * * @param transition the transition to apply, in serialized form * @param now the current timestamp * @param pool the pool to run any listeners on */ @Override public void applyTransition(byte[] transition, long now, ExecutorService pool) { try { KeyValueStateMachineProto.Transition serializedTransition = KeyValueStateMachineProto.Transition.parseFrom(transition); applyTransition(serializedTransition, now, pool); } catch (InvalidProtocolBufferException e) { log.warn("Attempting to deserialize an invalid transition! This is very bad. Leaving current state unchanged.", e); } } public void applyTransition(KeyValueStateMachineProto.Transition serializedTransition, long now, ExecutorService pool) { boolean shouldCallChangeListeners = false; switch (serializedTransition.getType()) { case TRANSITION_GROUP: for (KeyValueStateMachineProto.Transition transition : serializedTransition.getTransitionsList()) { applyTransition(transition, now, pool); } break; case REQUEST_LOCK: KeyValueStateMachineProto.RequestLock serializedRequestLock = serializedTransition.getRequestLock(); LockRequest requestLockRequest = new LockRequest(serializedRequestLock.getRequester(), serializedRequestLock.getUniqueHash()); synchronized (this) { // 1. If the QueueLock is not currently in the locks map in StateMachine (means it is currently not held), then the // requester gets it immediately. if (!locks.containsKey(serializedRequestLock.getLock())) { QueueLock lock = new QueueLock(Optional.of(requestLockRequest), new ArrayList<>()); locks.put(serializedRequestLock.getLock(), lock); } // 2. Otherwise, add the requester to the waiting list of the QueueLock else { QueueLock lock = locks.get(serializedRequestLock.getLock()); if (!lock.waiting.contains(requestLockRequest) && (!lock.holder.isPresent() || !lock.holder.get().equals(requestLockRequest))) { lock.waiting.add(requestLockRequest); } } // 3. Check if there are any CompletableFutures outstanding waiting for this lock to be acquired checkLocksAcquired(pool, serializedRequestLock.getLock()); } break; case RELEASE_LOCK: KeyValueStateMachineProto.ReleaseLock serializedReleaseLock = serializedTransition.getReleaseLock(); synchronized (this) { if (locks.containsKey(serializedReleaseLock.getLock())) { QueueLock lock = locks.get(serializedReleaseLock.getLock()); // 1. If the QueueLock is held by a different requester, this is a no-op //noinspection ConstantConditions,OptionalGetWithoutIsPresent if (lock.holder.isPresent() && lock.holder.get().server.equals(serializedReleaseLock.getRequester()) && lock.holder.get().uniqueHash.equals(serializedReleaseLock.getUniqueHash())) { // 2. Release the lock releaseLock(serializedReleaseLock.getLock(), pool); } else { // 3. Check if the list of waiters on the lock contains the releaser, if so stop waiting Optional<LockRequest> requestToRemove = Optional.empty(); for (LockRequest request : lock.waiting) { if (request.server.equals(serializedReleaseLock.getRequester()) && request.uniqueHash.equals(serializedReleaseLock.getUniqueHash())) { requestToRemove = Optional.of(request); } } requestToRemove.ifPresent(lockRequest -> lock.waiting.remove(lockRequest)); if (!requestToRemove.isPresent()) { log.warn("Received a release lock command that will not result in any action - this is fine, but should be rare"); } } } else { log.warn("Received a release lock command that will not result in any action - this is fine, but should be rare"); } } break; case TRY_LOCK: KeyValueStateMachineProto.TryLock serializedTryLock = serializedTransition.getTryLock(); LockRequest requestTryLock = new LockRequest(serializedTryLock.getRequester(), serializedTryLock.getUniqueHash()); synchronized (this) { // 1. If the QueueLock is not currently in the locks map in StateMachine (means it is currently not held), then the // requester gets it immediately. if (!locks.containsKey(serializedTryLock.getLock())) { QueueLock lock = new QueueLock(Optional.of(requestTryLock), new ArrayList<>()); locks.put(serializedTryLock.getLock(), lock); } // 2. Check if there are any CompletableFutures outstanding waiting for this lock to be acquired checkLocksAcquired(pool, serializedTryLock.getLock()); } break; case SET_VALUE: // Set a value KeyValueStateMachineProto.SetValue serializedSetValue = serializedTransition.getSetValue(); ValueWithOptionalOwner valueWithOptionalOwner; if (serializedSetValue.getOwner().equals("")) { valueWithOptionalOwner = new ValueWithOptionalOwner(serializedSetValue.getValue().toByteArray(), now); } else { valueWithOptionalOwner = new ValueWithOptionalOwner(serializedSetValue.getValue().toByteArray(), serializedSetValue.getOwner(), now); } if (!values.containsKey(serializedSetValue.getKey()) || !values.get(serializedSetValue.getKey()).equals(valueWithOptionalOwner)) { shouldCallChangeListeners = true; } values.put(serializedSetValue.getKey(), valueWithOptionalOwner); break; case REMOVE_VALUE: // Remove a value KeyValueStateMachineProto.RemoveValue serializedRemoveValue = serializedTransition.getRemoveValue(); if (values.containsKey(serializedRemoveValue.getKey())) { shouldCallChangeListeners = true; } values.remove(serializedRemoveValue.getKey()); break; case CLEAR_TRANSIENTS: // Clear transient entries for a user synchronized (this) { this.clearTransientsFor(serializedTransition.getClearTransients().getOwner(), pool); } break; case UNRECOGNIZED: case INVALID: // Unknown transition log.warn("Unrecognized transition type "+serializedTransition.getType()+"! This is very bad. Leaving current state unchanged."); break; } // If we're changing the map value, then call all the change listeners if (shouldCallChangeListeners) { Set<ChangeListener> changeListenersCopy; synchronized (changeListeners) { changeListenersCopy = new HashSet<>(changeListeners); } if (changeListenersCopy.size() > 0) { Map<String, byte[]> asMap = new ValueWithOptionalOwnerMapView(this.values); for (ChangeListener listener : changeListenersCopy) { if (serializedTransition.getType() == KeyValueStateMachineProto.TransitionType.SET_VALUE) { // Set a value pool.execute(() -> listener.onChange(serializedTransition.getSetValue().getKey(), Optional.of(serializedTransition.getSetValue().getValue().toByteArray()), asMap)); } else if (serializedTransition.getType() == KeyValueStateMachineProto.TransitionType.REMOVE_VALUE) { // Clear a value pool.execute(() -> listener.onChange(serializedTransition.getRemoveValue().getKey(), Optional.empty(), asMap)); } else { log.warn("We should be calling a change listener, but the transition doesn't seem to warrant an update"); } } } } } /** * This registers a listener that will be called whenever the key-value store changes. * * @param changeListener the listener to register */ public void addChangeListener(ChangeListener changeListener) { int numListeners; synchronized (this.changeListeners) { // Add the listener this.changeListeners.add(changeListener); numListeners = this.changeListeners.size(); assert this.changeListeners.contains(changeListener); this.changeListenerToTrace.put(changeListener, new StackTrace()); assert this.changeListenerToTrace.containsKey(changeListener); // Register the listener in Prometheus Prometheus.gaugeSet(gaugeNumListeners, (double) numListeners); } // Make sure we don't have too many listeners if (numListeners > 256) { throwRaftError("too-many-raft-listeners-" + SystemUtils.HOST, "Too many Raft listeners: Listener count at : " + numListeners); } } /** * This removes a listener that will be called whenever the key-value store changes. * * @param changeListener the listener to deregister */ public void removeChangeListener(ChangeListener changeListener) {synchronized (this.changeListeners) { // Deregister the listener. int numListeners; synchronized (this.changeListeners) { if (!this.changeListeners.remove(changeListener)) { log.warn("Removing a change listener that isn't registered"); } if (this.changeListenerToTrace.remove(changeListener) == null) { log.warn("Could not find change listener in stack trace mapping"); } numListeners = this.changeListeners.size(); } // Deregister the listener in Prometheus Prometheus.gaugeSet(gaugeNumListeners, (double) numListeners); } } /** * This gets a value from the values map, if it's present. Otherwise returns empty. * * @param key The key to retrieve. * @param now The current time, so that we can mock transport time if appropriate. * * @return the value, or empty */ public Optional<byte[]> get(String key, long now) { return Optional.ofNullable(values.getOrDefault(key, null)).map(v -> v.registerGet(now)); /* if (values.containsKey(key)) return Optional.of(values.get(key).registerGet(now)); else return Optional.empty(); */ } /** * This gets the current set of keys in the state machine. */ public Collection<String> keys() { return values.keySet(); } /** * This returns a copy of the key-&gt;value map in the state machine. */ public Map<String, byte[]> map() { return new ValueWithOptionalOwnerMapView(new HashMap<>(this.values)); } /** * Returns entries which have not been modified in at least |age| amount of time. * * @param idleTime The amount of time an entry must have been idle in the state machine. * @param now The current time. */ public Set<String> keysIdleSince(Duration idleTime, long now) { Set<String> keys = new HashSet<>(); for (Map.Entry<String, ValueWithOptionalOwner> entry : values.entrySet()) { if (entry.getValue().lastAccessed + idleTime.toMillis() < now) { keys.add(entry.getKey()); } } return keys; } /** * Returns entries which have not been modified in at least |age| amount of time. * * @param timeInRaft The amount of time an entry must have been in the state machine. * @param now The current time. */ public Set<String> keysPresentSince(Duration timeInRaft, long now) { Set<String> keys = new HashSet<>(); for (Map.Entry<String, ValueWithOptionalOwner> entry : values.entrySet()) { if (entry.getValue().createdAt + timeInRaft.toMillis() < now) { keys.add(entry.getKey()); } } return keys; } /** * This returns the full list of entries in the state machine. * This is threadsafe, insofar as it comes from a {@link ConcurrentHashMap}. */ public Collection<Map.Entry<String, ValueWithOptionalOwner>> entries() { return values.entrySet(); } /** * This releases a lock in the state machine. */ private void releaseLock(String lockName, ExecutorService pool) { if (locks.containsKey(lockName)) { QueueLock lock = locks.get(lockName); if (lock.waiting.size() > 0) { // 1. If the QueueLock waiting list is non-empty, then the next in the waiting list gets the lock immediately, and is // removed from the waiting list. LockRequest nextUp = lock.waiting.get(0); lock.waiting.remove(0); lock.holder = Optional.of(nextUp); } else { // 2. Otherwise, remove the lock from the locks map in StateMachine locks.remove(lockName); } } // 3. Releasing the lock may trigger a Future checkLocksAcquired(pool, lockName); } /** * This gets called when we detect that a machine has gone down, and we should remove all of the transient entries * and locks pertaining to that machine. * * @param owner The machine that has gone down that we should clear. */ private synchronized void clearTransientsFor(String owner, ExecutorService pool) { // 1. Error checks if (serverName.map(sn -> Objects.equals(sn, owner)).orElse(false)) { log.warn("Got a Raft transition telling us we're offline. We are, of course, not offline. All transient state owned by us is being cleared."); } // 2. Remove any values that are owned by people who are now disconnected Set<String> keysToRemove = new HashSet<>(); values.forEach((key, value) -> { if (value.owner.map(x -> Objects.equals(x, owner)).orElse(false)) { keysToRemove.add(key); } }); for (String key : keysToRemove) { values.remove(key); } // 3. Scrub any mention of people who are no longer in the committedClusterMembers from the locks Map<String, QueueLock> locks = new HashMap<>(this.locks); // copy the locks map to avoid ConcurrentModificationException when releaseLock() modifies locks below locks.values() .forEach(lock -> lock.waiting.removeIf(req -> Objects.equals(req.server, owner))); locks.entrySet().stream() .filter(lock -> lock.getValue().holder.map(h -> Objects.equals(h.server, owner)).orElse(false)) .forEach(x -> releaseLock(x.getKey(), pool)); } /** {@inheritDoc} */ @Override public Set<String> owners() { Set<String> seen = new HashSet<>(); locks.forEach((key, lock) -> { if (lock.holder.isPresent()) { String holder = lock.holder.get().server; seen.add(holder); } }); values.forEach((key, value) -> { if (value.owner.isPresent()) { String holder = value.owner.get(); seen.add(holder); } }); return seen; } /** {@inheritDoc} */ @Override public String debugTransition(byte[] transition) { try { KeyValueStateMachineProto.Transition serializedTransition = KeyValueStateMachineProto.Transition.parseFrom(transition); if (serializedTransition.getType() == KeyValueStateMachineProto.TransitionType.REQUEST_LOCK) { return serializedTransition.getRequestLock().getRequester()+" requests lock '"+serializedTransition.getRequestLock().getLock()+"' with hash "+serializedTransition.getRequestLock().getUniqueHash(); } else if (serializedTransition.getType() == KeyValueStateMachineProto.TransitionType.RELEASE_LOCK) { return serializedTransition.getReleaseLock().getRequester()+" releases lock '"+serializedTransition.getReleaseLock().getLock()+"' with hash "+serializedTransition.getReleaseLock().getUniqueHash(); } else if (serializedTransition.getType() == KeyValueStateMachineProto.TransitionType.SET_VALUE) { return "set "+serializedTransition.getSetValue().getKey()+" = '"+serializedTransition.getSetValue().getValue().toStringUtf8() + "'"; } else if (serializedTransition.getType() == KeyValueStateMachineProto.TransitionType.REMOVE_VALUE) { return "remove "+serializedTransition.getRemoveValue().getKey(); } else { return "Unrecognized - type "+serializedTransition.getType(); } } catch (InvalidProtocolBufferException e) { return "Unrecognized - invalid proto"; } } /** * Release a single lock. */ private void completeLockFuture(@Nullable ExecutorService pool, QueueLock lock, LockAcquiredFuture future) { if (lock.holder.isPresent() && lock.holder.get().server.equals(future.requester) && lock.holder.get().uniqueHash.equals(future.uniqueHash)) { synchronized (lockAcquiredFutures) { lockAcquiredFutures.remove(future); } if (pool == null) { future.future.complete(true); } else { pool.execute(() -> future.future.complete(true)); } } else if (!lock.holder.isPresent()) { // Lock has no holder, so if we're waiting on it that implies we're hosed synchronized (lockAcquiredFutures) { lockAcquiredFutures.remove(future); } if (pool == null) { future.future.complete(false); } else { pool.execute(() -> future.future.complete(false)); } } // Lock has a holder, and that holder isn't us. Continue waiting } private void checkLocksAcquired(ExecutorService pool, String lockName) { List<LockAcquiredFuture> originalLockAcquiredFutures; synchronized (lockAcquiredFutures) { originalLockAcquiredFutures = new ArrayList<>(lockAcquiredFutures); } for (LockAcquiredFuture future : new ArrayList<>(originalLockAcquiredFutures)) { if (lockName.equals(future.lock)) { QueueLock lock = locks.get(lockName); if (lock != null) { // Case: try to complete this lock's future completeLockFuture(pool, lock, future); } else { // Case: this lock no longer exists -- it must be released. pool.execute(() -> future.future.complete(false)); } } } } /** * This iterates over our list of LockAcquiredFutures and completes and removes any of them that are now satisfied. */ private void checkLocksAcquired(ExecutorService pool) { List<LockAcquiredFuture> originalLockAcquiredFutures; synchronized (lockAcquiredFutures) { originalLockAcquiredFutures = new ArrayList<>(lockAcquiredFutures); } List<LockAcquiredFuture> toRemove = new ArrayList<>(); for (LockAcquiredFuture future : new ArrayList<>(originalLockAcquiredFutures)) { QueueLock lock = locks.get(future.lock); if (lock != null) { completeLockFuture(pool, lock, future); } else { // Lock was removed, so this is impossible to acquire toRemove.add(future); pool.execute(() -> future.future.complete(false)); } } synchronized (lockAcquiredFutures) { lockAcquiredFutures.removeAll(toRemove); } } /** {@inheritDoc} */ @Override public synchronized boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; KeyValueStateMachine that = (KeyValueStateMachine) o; return Objects.equals(values, that.values) && Objects.equals(locks, that.locks); } /** {@inheritDoc} */ @Override public synchronized int hashCode() { return Objects.hash(values, locks); } /** * <p> * This creates a future that completes as soon as the specified requester is granted the specified lock in our * committed view of the world. This completes with true once you've acquired the lock, or false if it appears that * you are no longer waiting on the lock (for example, if you were disconnected from the cluster while waiting your * request for the lock could have been deleted). * </p> * * <p> * If this lock does not exist in {@link #locks} yet, we create the lock lazily and wait on it. * This means that <b>waiting on a lock that has already been released or will never be acquired will wait forever</b>. * </p> * * @param lock the lock we're interested in * @param requester the requester who will acquire the lock * @param uniqueHash the unique hash to deduplicate requests on the same machine * * @return a Future that completes when the lock is acquired by requester. */ CompletableFuture<Boolean> createLockAcquiredFuture(String lock, String requester, String uniqueHash) { // 1. Register the future CompletableFuture<Boolean> lockAcquiredFuture = new CompletableFuture<>(); LockAcquiredFuture lockAcquiredFutureObj = new LockAcquiredFuture(lock, requester, uniqueHash, lockAcquiredFuture); synchronized (lockAcquiredFutures) { this.lockAcquiredFutures.add(lockAcquiredFutureObj); } // 2. Check for immediate completiong QueueLock lockObj = locks.get(lock); if (lockObj != null) { completeLockFuture(null, lockObj, lockAcquiredFutureObj); } // 3. Return return lockAcquiredFuture; } /** * This creates a serialized RequestLock transition. * * @param lock the lock name * @param requester the requester of the lock * @param uniqueHash the unique hash to deduplicate requests on the same machine * @return a serialized RequestLock transition */ public static byte[] createRequestLockTransition(String lock, String requester, String uniqueHash) { KeyValueStateMachineProto.Transition.Builder transitionBuilder = KeyValueStateMachineProto.Transition.newBuilder(); transitionBuilder.setType(KeyValueStateMachineProto.TransitionType.REQUEST_LOCK); KeyValueStateMachineProto.RequestLock.Builder requestLockBuilder = KeyValueStateMachineProto.RequestLock.newBuilder(); requestLockBuilder.setLock(lock); requestLockBuilder.setRequester(requester); requestLockBuilder.setUniqueHash(uniqueHash); transitionBuilder.setRequestLock(requestLockBuilder); return transitionBuilder.build().toByteArray(); } /** * This creates a serialized TryLock transition. * * @param lock the lock name * @param requester the requester of the lock * @param uniqueHash the unique hash to deduplicate requests on the same machine * @return a serialized RequestLock transition */ public static byte[] createTryLockTransition(String lock, String requester, String uniqueHash) { KeyValueStateMachineProto.Transition.Builder transitionBuilder = KeyValueStateMachineProto.Transition.newBuilder(); transitionBuilder.setType(KeyValueStateMachineProto.TransitionType.TRY_LOCK); KeyValueStateMachineProto.TryLock.Builder tryLockBuilder = KeyValueStateMachineProto.TryLock.newBuilder(); tryLockBuilder.setLock(lock); tryLockBuilder.setRequester(requester); tryLockBuilder.setUniqueHash(uniqueHash); transitionBuilder.setTryLock(tryLockBuilder); return transitionBuilder.build().toByteArray(); } /** * This creates a serialized ReleaseLock transition. * * @param lock the lock name * @param requester the requester of the lock * @param uniqueHash the unique hash to deduplicate requests on the same machine * @return a serialized ReleaseLock transition */ public static byte[] createReleaseLockTransition(String lock, String requester, String uniqueHash) { KeyValueStateMachineProto.Transition.Builder transitionBuilder = KeyValueStateMachineProto.Transition.newBuilder(); transitionBuilder.setType(KeyValueStateMachineProto.TransitionType.RELEASE_LOCK); KeyValueStateMachineProto.ReleaseLock.Builder requestLockBuilder = KeyValueStateMachineProto.ReleaseLock.newBuilder(); requestLockBuilder.setLock(lock); requestLockBuilder.setRequester(requester); requestLockBuilder.setUniqueHash(uniqueHash); transitionBuilder.setReleaseLock(requestLockBuilder); return transitionBuilder.build().toByteArray(); } /** * Creates a grouped transition, which executes several transitions atomically. * * @param transitions the transitions (serialized) to group * @return a grouped transition */ public static byte[] createGroupedTransition(byte[]... transitions) { KeyValueStateMachineProto.Transition.Builder transitionBuilder = KeyValueStateMachineProto.Transition.newBuilder(); transitionBuilder.setType(KeyValueStateMachineProto.TransitionType.TRANSITION_GROUP); for (byte[] transition : transitions) { try { transitionBuilder.addTransitions(KeyValueStateMachineProto.Transition.parseFrom(transition)); } catch (InvalidProtocolBufferException e) { log.warn("Unable to parse"); } } return transitionBuilder.build().toByteArray(); } /** * This creates a serialized SetValue transition that will set an entry in the values map, with an "owner" who is * responsible for the value, which will be automatically cleaned up when the owner disconnects from the cluster. * * @param key the key to set * @param value the value, as a raw byte array * @param owner the owner of this key-value pair * @return a serialized SetValue transition */ public static byte[] createSetValueTransitionWithOwner(String key, byte[] value, String owner) { KeyValueStateMachineProto.Transition.Builder transitionBuilder = KeyValueStateMachineProto.Transition.newBuilder(); transitionBuilder.setType(KeyValueStateMachineProto.TransitionType.SET_VALUE); KeyValueStateMachineProto.SetValue.Builder setValueBuilder = KeyValueStateMachineProto.SetValue.newBuilder(); setValueBuilder.setKey(key); setValueBuilder.setValue(ByteString.copyFrom(value)); setValueBuilder.setOwner(owner); transitionBuilder.setSetValue(setValueBuilder); return transitionBuilder.build().toByteArray(); } /** * This creates a serialized SetValue transition that will set an entry in the values map. * * @param key the key to set * @param value the value, as a raw byte array * @return a serialized SetValue transition */ public static byte[] createSetValueTransition(String key, byte[] value) { KeyValueStateMachineProto.Transition.Builder transitionBuilder = KeyValueStateMachineProto.Transition.newBuilder(); transitionBuilder.setType(KeyValueStateMachineProto.TransitionType.SET_VALUE); KeyValueStateMachineProto.SetValue.Builder setValueBuilder = KeyValueStateMachineProto.SetValue.newBuilder(); setValueBuilder.setKey(key); setValueBuilder.setValue(ByteString.copyFrom(value)); transitionBuilder.setSetValue(setValueBuilder); return transitionBuilder.build().toByteArray(); } /** * This creates a serialized RemoveValue transition that will delete an entry in the map, if it's currently present. * * @param key the key to remove * @return a serialized RemoveValue transition */ public static byte[] createRemoveValueTransition(String key) { KeyValueStateMachineProto.Transition.Builder transitionBuilder = KeyValueStateMachineProto.Transition.newBuilder(); transitionBuilder.setType(KeyValueStateMachineProto.TransitionType.REMOVE_VALUE); KeyValueStateMachineProto.RemoveValue.Builder removeValueBuilder = KeyValueStateMachineProto.RemoveValue.newBuilder(); removeValueBuilder.setKey(key); transitionBuilder.setRemoveValue(removeValueBuilder); return transitionBuilder.build().toByteArray(); } /** * This creates a serialized ClearTransient transition. * * @param owner the owner we should clear transient values for. * * @return a serialized ClearTransient transition */ public static byte[] createClearTransition(String owner) { return KeyValueStateMachineProto.Transition.newBuilder() .setType(KeyValueStateMachineProto.TransitionType.CLEAR_TRANSIENTS) .setClearTransients(KeyValueStateMachineProto.ClearTransients.newBuilder() .setOwner(owner) ) .build().toByteArray(); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/KeyValueStateMachineProto.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: KeyValueStateMachine.proto package ai.eloquent.raft; public final class KeyValueStateMachineProto { private KeyValueStateMachineProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } /** * Protobuf enum {@code ai.eloquent.raft.TransitionType} */ public enum TransitionType implements com.google.protobuf.ProtocolMessageEnum { /** * <code>INVALID = 0;</code> */ INVALID(0), /** * <pre> * was 0, before INVALID was added * </pre> * * <code>REQUEST_LOCK = 6;</code> */ REQUEST_LOCK(6), /** * <code>RELEASE_LOCK = 1;</code> */ RELEASE_LOCK(1), /** * <code>TRY_LOCK = 2;</code> */ TRY_LOCK(2), /** * <code>SET_VALUE = 3;</code> */ SET_VALUE(3), /** * <code>REMOVE_VALUE = 4;</code> */ REMOVE_VALUE(4), /** * <code>CLEAR_TRANSIENTS = 5;</code> */ CLEAR_TRANSIENTS(5), /** * <code>TRANSITION_GROUP = 7;</code> */ TRANSITION_GROUP(7), UNRECOGNIZED(-1), ; /** * <code>INVALID = 0;</code> */ public static final int INVALID_VALUE = 0; /** * <pre> * was 0, before INVALID was added * </pre> * * <code>REQUEST_LOCK = 6;</code> */ public static final int REQUEST_LOCK_VALUE = 6; /** * <code>RELEASE_LOCK = 1;</code> */ public static final int RELEASE_LOCK_VALUE = 1; /** * <code>TRY_LOCK = 2;</code> */ public static final int TRY_LOCK_VALUE = 2; /** * <code>SET_VALUE = 3;</code> */ public static final int SET_VALUE_VALUE = 3; /** * <code>REMOVE_VALUE = 4;</code> */ public static final int REMOVE_VALUE_VALUE = 4; /** * <code>CLEAR_TRANSIENTS = 5;</code> */ public static final int CLEAR_TRANSIENTS_VALUE = 5; /** * <code>TRANSITION_GROUP = 7;</code> */ public static final int TRANSITION_GROUP_VALUE = 7; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static TransitionType valueOf(int value) { return forNumber(value); } public static TransitionType forNumber(int value) { switch (value) { case 0: return INVALID; case 6: return REQUEST_LOCK; case 1: return RELEASE_LOCK; case 2: return TRY_LOCK; case 3: return SET_VALUE; case 4: return REMOVE_VALUE; case 5: return CLEAR_TRANSIENTS; case 7: return TRANSITION_GROUP; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<TransitionType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< TransitionType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<TransitionType>() { public TransitionType findValueByNumber(int number) { return TransitionType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.getDescriptor().getEnumTypes().get(0); } private static final TransitionType[] VALUES = values(); public static TransitionType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private TransitionType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:ai.eloquent.raft.TransitionType) } public interface KVStateMachineOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.KVStateMachine) com.google.protobuf.MessageOrBuilder { /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ int getValuesCount(); /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ boolean containsValues( java.lang.String key); /** * Use {@link #getValuesMap()} instead. */ @java.lang.Deprecated java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> getValues(); /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> getValuesMap(); /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getValuesOrDefault( java.lang.String key, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner defaultValue); /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getValuesOrThrow( java.lang.String key); /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ int getLocksCount(); /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ boolean containsLocks( java.lang.String key); /** * Use {@link #getLocksMap()} instead. */ @java.lang.Deprecated java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> getLocks(); /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> getLocksMap(); /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getLocksOrDefault( java.lang.String key, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock defaultValue); /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getLocksOrThrow( java.lang.String key); /** * <code>repeated string valuesKeys = 3;</code> */ java.util.List<java.lang.String> getValuesKeysList(); /** * <code>repeated string valuesKeys = 3;</code> */ int getValuesKeysCount(); /** * <code>repeated string valuesKeys = 3;</code> */ java.lang.String getValuesKeys(int index); /** * <code>repeated string valuesKeys = 3;</code> */ com.google.protobuf.ByteString getValuesKeysBytes(int index); /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> getValuesValuesList(); /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getValuesValues(int index); /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ int getValuesValuesCount(); /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwnerOrBuilder> getValuesValuesOrBuilderList(); /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwnerOrBuilder getValuesValuesOrBuilder( int index); /** * <code>repeated string locksKeys = 5;</code> */ java.util.List<java.lang.String> getLocksKeysList(); /** * <code>repeated string locksKeys = 5;</code> */ int getLocksKeysCount(); /** * <code>repeated string locksKeys = 5;</code> */ java.lang.String getLocksKeys(int index); /** * <code>repeated string locksKeys = 5;</code> */ com.google.protobuf.ByteString getLocksKeysBytes(int index); /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> getLocksValuesList(); /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getLocksValues(int index); /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ int getLocksValuesCount(); /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.QueueLockOrBuilder> getLocksValuesOrBuilderList(); /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.QueueLockOrBuilder getLocksValuesOrBuilder( int index); } /** * Protobuf type {@code ai.eloquent.raft.KVStateMachine} */ public static final class KVStateMachine extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.KVStateMachine) KVStateMachineOrBuilder { private static final long serialVersionUID = 0L; // Use KVStateMachine.newBuilder() to construct. private KVStateMachine(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private KVStateMachine() { valuesKeys_ = com.google.protobuf.LazyStringArrayList.EMPTY; valuesValues_ = java.util.Collections.emptyList(); locksKeys_ = com.google.protobuf.LazyStringArrayList.EMPTY; locksValues_ = java.util.Collections.emptyList(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private KVStateMachine( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { values_ = com.google.protobuf.MapField.newMapField( ValuesDefaultEntryHolder.defaultEntry); mutable_bitField0_ |= 0x00000001; } com.google.protobuf.MapEntry<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> values__ = input.readMessage( ValuesDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); values_.getMutableMap().put( values__.getKey(), values__.getValue()); break; } case 18: { if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { locks_ = com.google.protobuf.MapField.newMapField( LocksDefaultEntryHolder.defaultEntry); mutable_bitField0_ |= 0x00000002; } com.google.protobuf.MapEntry<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> locks__ = input.readMessage( LocksDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); locks_.getMutableMap().put( locks__.getKey(), locks__.getValue()); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { valuesKeys_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000004; } valuesKeys_.add(s); break; } case 34: { if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { valuesValues_ = new java.util.ArrayList<ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner>(); mutable_bitField0_ |= 0x00000008; } valuesValues_.add( input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.parser(), extensionRegistry)); break; } case 42: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) { locksKeys_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000010; } locksKeys_.add(s); break; } case 50: { if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) { locksValues_ = new java.util.ArrayList<ai.eloquent.raft.KeyValueStateMachineProto.QueueLock>(); mutable_bitField0_ |= 0x00000020; } locksValues_.add( input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.parser(), extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { valuesKeys_ = valuesKeys_.getUnmodifiableView(); } if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { valuesValues_ = java.util.Collections.unmodifiableList(valuesValues_); } if (((mutable_bitField0_ & 0x00000010) == 0x00000010)) { locksKeys_ = locksKeys_.getUnmodifiableView(); } if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) { locksValues_ = java.util.Collections.unmodifiableList(locksValues_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_KVStateMachine_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMapField( int number) { switch (number) { case 1: return internalGetValues(); case 2: return internalGetLocks(); default: throw new RuntimeException( "Invalid map field number: " + number); } } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_KVStateMachine_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine.class, ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine.Builder.class); } public static final int VALUES_FIELD_NUMBER = 1; private static final class ValuesDefaultEntryHolder { static final com.google.protobuf.MapEntry< java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> defaultEntry = com.google.protobuf.MapEntry .<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner>newDefaultInstance( ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_KVStateMachine_ValuesEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.MESSAGE, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.getDefaultInstance()); } private com.google.protobuf.MapField< java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> values_; private com.google.protobuf.MapField<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> internalGetValues() { if (values_ == null) { return com.google.protobuf.MapField.emptyMapField( ValuesDefaultEntryHolder.defaultEntry); } return values_; } public int getValuesCount() { return internalGetValues().getMap().size(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public boolean containsValues( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } return internalGetValues().getMap().containsKey(key); } /** * Use {@link #getValuesMap()} instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> getValues() { return getValuesMap(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> getValuesMap() { return internalGetValues().getMap(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getValuesOrDefault( java.lang.String key, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner defaultValue) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> map = internalGetValues().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getValuesOrThrow( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> map = internalGetValues().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public static final int LOCKS_FIELD_NUMBER = 2; private static final class LocksDefaultEntryHolder { static final com.google.protobuf.MapEntry< java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> defaultEntry = com.google.protobuf.MapEntry .<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock>newDefaultInstance( ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_KVStateMachine_LocksEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.MESSAGE, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.getDefaultInstance()); } private com.google.protobuf.MapField< java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> locks_; private com.google.protobuf.MapField<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> internalGetLocks() { if (locks_ == null) { return com.google.protobuf.MapField.emptyMapField( LocksDefaultEntryHolder.defaultEntry); } return locks_; } public int getLocksCount() { return internalGetLocks().getMap().size(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public boolean containsLocks( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } return internalGetLocks().getMap().containsKey(key); } /** * Use {@link #getLocksMap()} instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> getLocks() { return getLocksMap(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> getLocksMap() { return internalGetLocks().getMap(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getLocksOrDefault( java.lang.String key, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock defaultValue) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> map = internalGetLocks().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getLocksOrThrow( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> map = internalGetLocks().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public static final int VALUESKEYS_FIELD_NUMBER = 3; private com.google.protobuf.LazyStringList valuesKeys_; /** * <code>repeated string valuesKeys = 3;</code> */ public com.google.protobuf.ProtocolStringList getValuesKeysList() { return valuesKeys_; } /** * <code>repeated string valuesKeys = 3;</code> */ public int getValuesKeysCount() { return valuesKeys_.size(); } /** * <code>repeated string valuesKeys = 3;</code> */ public java.lang.String getValuesKeys(int index) { return valuesKeys_.get(index); } /** * <code>repeated string valuesKeys = 3;</code> */ public com.google.protobuf.ByteString getValuesKeysBytes(int index) { return valuesKeys_.getByteString(index); } public static final int VALUESVALUES_FIELD_NUMBER = 4; private java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> valuesValues_; /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> getValuesValuesList() { return valuesValues_; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwnerOrBuilder> getValuesValuesOrBuilderList() { return valuesValues_; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public int getValuesValuesCount() { return valuesValues_.size(); } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getValuesValues(int index) { return valuesValues_.get(index); } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwnerOrBuilder getValuesValuesOrBuilder( int index) { return valuesValues_.get(index); } public static final int LOCKSKEYS_FIELD_NUMBER = 5; private com.google.protobuf.LazyStringList locksKeys_; /** * <code>repeated string locksKeys = 5;</code> */ public com.google.protobuf.ProtocolStringList getLocksKeysList() { return locksKeys_; } /** * <code>repeated string locksKeys = 5;</code> */ public int getLocksKeysCount() { return locksKeys_.size(); } /** * <code>repeated string locksKeys = 5;</code> */ public java.lang.String getLocksKeys(int index) { return locksKeys_.get(index); } /** * <code>repeated string locksKeys = 5;</code> */ public com.google.protobuf.ByteString getLocksKeysBytes(int index) { return locksKeys_.getByteString(index); } public static final int LOCKSVALUES_FIELD_NUMBER = 6; private java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> locksValues_; /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> getLocksValuesList() { return locksValues_; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.QueueLockOrBuilder> getLocksValuesOrBuilderList() { return locksValues_; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public int getLocksValuesCount() { return locksValues_.size(); } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getLocksValues(int index) { return locksValues_.get(index); } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLockOrBuilder getLocksValuesOrBuilder( int index) { return locksValues_.get(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { com.google.protobuf.GeneratedMessageV3 .serializeStringMapTo( output, internalGetValues(), ValuesDefaultEntryHolder.defaultEntry, 1); com.google.protobuf.GeneratedMessageV3 .serializeStringMapTo( output, internalGetLocks(), LocksDefaultEntryHolder.defaultEntry, 2); for (int i = 0; i < valuesKeys_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, valuesKeys_.getRaw(i)); } for (int i = 0; i < valuesValues_.size(); i++) { output.writeMessage(4, valuesValues_.get(i)); } for (int i = 0; i < locksKeys_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, locksKeys_.getRaw(i)); } for (int i = 0; i < locksValues_.size(); i++) { output.writeMessage(6, locksValues_.get(i)); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (java.util.Map.Entry<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> entry : internalGetValues().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> values__ = ValuesDefaultEntryHolder.defaultEntry.newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, values__); } for (java.util.Map.Entry<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> entry : internalGetLocks().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> locks__ = LocksDefaultEntryHolder.defaultEntry.newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, locks__); } { int dataSize = 0; for (int i = 0; i < valuesKeys_.size(); i++) { dataSize += computeStringSizeNoTag(valuesKeys_.getRaw(i)); } size += dataSize; size += 1 * getValuesKeysList().size(); } for (int i = 0; i < valuesValues_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, valuesValues_.get(i)); } { int dataSize = 0; for (int i = 0; i < locksKeys_.size(); i++) { dataSize += computeStringSizeNoTag(locksKeys_.getRaw(i)); } size += dataSize; size += 1 * getLocksKeysList().size(); } for (int i = 0; i < locksValues_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(6, locksValues_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine other = (ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine) obj; boolean result = true; result = result && internalGetValues().equals( other.internalGetValues()); result = result && internalGetLocks().equals( other.internalGetLocks()); result = result && getValuesKeysList() .equals(other.getValuesKeysList()); result = result && getValuesValuesList() .equals(other.getValuesValuesList()); result = result && getLocksKeysList() .equals(other.getLocksKeysList()); result = result && getLocksValuesList() .equals(other.getLocksValuesList()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (!internalGetValues().getMap().isEmpty()) { hash = (37 * hash) + VALUES_FIELD_NUMBER; hash = (53 * hash) + internalGetValues().hashCode(); } if (!internalGetLocks().getMap().isEmpty()) { hash = (37 * hash) + LOCKS_FIELD_NUMBER; hash = (53 * hash) + internalGetLocks().hashCode(); } if (getValuesKeysCount() > 0) { hash = (37 * hash) + VALUESKEYS_FIELD_NUMBER; hash = (53 * hash) + getValuesKeysList().hashCode(); } if (getValuesValuesCount() > 0) { hash = (37 * hash) + VALUESVALUES_FIELD_NUMBER; hash = (53 * hash) + getValuesValuesList().hashCode(); } if (getLocksKeysCount() > 0) { hash = (37 * hash) + LOCKSKEYS_FIELD_NUMBER; hash = (53 * hash) + getLocksKeysList().hashCode(); } if (getLocksValuesCount() > 0) { hash = (37 * hash) + LOCKSVALUES_FIELD_NUMBER; hash = (53 * hash) + getLocksValuesList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.KVStateMachine} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.KVStateMachine) ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachineOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_KVStateMachine_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMapField( int number) { switch (number) { case 1: return internalGetValues(); case 2: return internalGetLocks(); default: throw new RuntimeException( "Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMutableMapField( int number) { switch (number) { case 1: return internalGetMutableValues(); case 2: return internalGetMutableLocks(); default: throw new RuntimeException( "Invalid map field number: " + number); } } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_KVStateMachine_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine.class, ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getValuesValuesFieldBuilder(); getLocksValuesFieldBuilder(); } } public Builder clear() { super.clear(); internalGetMutableValues().clear(); internalGetMutableLocks().clear(); valuesKeys_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); if (valuesValuesBuilder_ == null) { valuesValues_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000008); } else { valuesValuesBuilder_.clear(); } locksKeys_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000010); if (locksValuesBuilder_ == null) { locksValues_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { locksValuesBuilder_.clear(); } return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_KVStateMachine_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine build() { ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine result = new ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine(this); int from_bitField0_ = bitField0_; result.values_ = internalGetValues(); result.values_.makeImmutable(); result.locks_ = internalGetLocks(); result.locks_.makeImmutable(); if (((bitField0_ & 0x00000004) == 0x00000004)) { valuesKeys_ = valuesKeys_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000004); } result.valuesKeys_ = valuesKeys_; if (valuesValuesBuilder_ == null) { if (((bitField0_ & 0x00000008) == 0x00000008)) { valuesValues_ = java.util.Collections.unmodifiableList(valuesValues_); bitField0_ = (bitField0_ & ~0x00000008); } result.valuesValues_ = valuesValues_; } else { result.valuesValues_ = valuesValuesBuilder_.build(); } if (((bitField0_ & 0x00000010) == 0x00000010)) { locksKeys_ = locksKeys_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000010); } result.locksKeys_ = locksKeys_; if (locksValuesBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { locksValues_ = java.util.Collections.unmodifiableList(locksValues_); bitField0_ = (bitField0_ & ~0x00000020); } result.locksValues_ = locksValues_; } else { result.locksValues_ = locksValuesBuilder_.build(); } onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine.getDefaultInstance()) return this; internalGetMutableValues().mergeFrom( other.internalGetValues()); internalGetMutableLocks().mergeFrom( other.internalGetLocks()); if (!other.valuesKeys_.isEmpty()) { if (valuesKeys_.isEmpty()) { valuesKeys_ = other.valuesKeys_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureValuesKeysIsMutable(); valuesKeys_.addAll(other.valuesKeys_); } onChanged(); } if (valuesValuesBuilder_ == null) { if (!other.valuesValues_.isEmpty()) { if (valuesValues_.isEmpty()) { valuesValues_ = other.valuesValues_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensureValuesValuesIsMutable(); valuesValues_.addAll(other.valuesValues_); } onChanged(); } } else { if (!other.valuesValues_.isEmpty()) { if (valuesValuesBuilder_.isEmpty()) { valuesValuesBuilder_.dispose(); valuesValuesBuilder_ = null; valuesValues_ = other.valuesValues_; bitField0_ = (bitField0_ & ~0x00000008); valuesValuesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getValuesValuesFieldBuilder() : null; } else { valuesValuesBuilder_.addAllMessages(other.valuesValues_); } } } if (!other.locksKeys_.isEmpty()) { if (locksKeys_.isEmpty()) { locksKeys_ = other.locksKeys_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureLocksKeysIsMutable(); locksKeys_.addAll(other.locksKeys_); } onChanged(); } if (locksValuesBuilder_ == null) { if (!other.locksValues_.isEmpty()) { if (locksValues_.isEmpty()) { locksValues_ = other.locksValues_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensureLocksValuesIsMutable(); locksValues_.addAll(other.locksValues_); } onChanged(); } } else { if (!other.locksValues_.isEmpty()) { if (locksValuesBuilder_.isEmpty()) { locksValuesBuilder_.dispose(); locksValuesBuilder_ = null; locksValues_ = other.locksValues_; bitField0_ = (bitField0_ & ~0x00000020); locksValuesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getLocksValuesFieldBuilder() : null; } else { locksValuesBuilder_.addAllMessages(other.locksValues_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private com.google.protobuf.MapField< java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> values_; private com.google.protobuf.MapField<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> internalGetValues() { if (values_ == null) { return com.google.protobuf.MapField.emptyMapField( ValuesDefaultEntryHolder.defaultEntry); } return values_; } private com.google.protobuf.MapField<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> internalGetMutableValues() { onChanged();; if (values_ == null) { values_ = com.google.protobuf.MapField.newMapField( ValuesDefaultEntryHolder.defaultEntry); } if (!values_.isMutable()) { values_ = values_.copy(); } return values_; } public int getValuesCount() { return internalGetValues().getMap().size(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public boolean containsValues( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } return internalGetValues().getMap().containsKey(key); } /** * Use {@link #getValuesMap()} instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> getValues() { return getValuesMap(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> getValuesMap() { return internalGetValues().getMap(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getValuesOrDefault( java.lang.String key, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner defaultValue) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> map = internalGetValues().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getValuesOrThrow( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> map = internalGetValues().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearValues() { internalGetMutableValues().getMutableMap() .clear(); return this; } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public Builder removeValues( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } internalGetMutableValues().getMutableMap() .remove(key); return this; } /** * Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> getMutableValues() { return internalGetMutableValues().getMutableMap(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public Builder putValues( java.lang.String key, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner value) { if (key == null) { throw new java.lang.NullPointerException(); } if (value == null) { throw new java.lang.NullPointerException(); } internalGetMutableValues().getMutableMap() .put(key, value); return this; } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.ValueWithOptionalOwner&gt; values = 1;</code> */ public Builder putAllValues( java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> values) { internalGetMutableValues().getMutableMap() .putAll(values); return this; } private com.google.protobuf.MapField< java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> locks_; private com.google.protobuf.MapField<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> internalGetLocks() { if (locks_ == null) { return com.google.protobuf.MapField.emptyMapField( LocksDefaultEntryHolder.defaultEntry); } return locks_; } private com.google.protobuf.MapField<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> internalGetMutableLocks() { onChanged();; if (locks_ == null) { locks_ = com.google.protobuf.MapField.newMapField( LocksDefaultEntryHolder.defaultEntry); } if (!locks_.isMutable()) { locks_ = locks_.copy(); } return locks_; } public int getLocksCount() { return internalGetLocks().getMap().size(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public boolean containsLocks( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } return internalGetLocks().getMap().containsKey(key); } /** * Use {@link #getLocksMap()} instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> getLocks() { return getLocksMap(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> getLocksMap() { return internalGetLocks().getMap(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getLocksOrDefault( java.lang.String key, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock defaultValue) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> map = internalGetLocks().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getLocksOrThrow( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> map = internalGetLocks().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearLocks() { internalGetMutableLocks().getMutableMap() .clear(); return this; } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public Builder removeLocks( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } internalGetMutableLocks().getMutableMap() .remove(key); return this; } /** * Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> getMutableLocks() { return internalGetMutableLocks().getMutableMap(); } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public Builder putLocks( java.lang.String key, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock value) { if (key == null) { throw new java.lang.NullPointerException(); } if (value == null) { throw new java.lang.NullPointerException(); } internalGetMutableLocks().getMutableMap() .put(key, value); return this; } /** * <pre> ** &#64;Deprecated * </pre> * * <code>map&lt;string, .ai.eloquent.raft.QueueLock&gt; locks = 2;</code> */ public Builder putAllLocks( java.util.Map<java.lang.String, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> values) { internalGetMutableLocks().getMutableMap() .putAll(values); return this; } private com.google.protobuf.LazyStringList valuesKeys_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureValuesKeysIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { valuesKeys_ = new com.google.protobuf.LazyStringArrayList(valuesKeys_); bitField0_ |= 0x00000004; } } /** * <code>repeated string valuesKeys = 3;</code> */ public com.google.protobuf.ProtocolStringList getValuesKeysList() { return valuesKeys_.getUnmodifiableView(); } /** * <code>repeated string valuesKeys = 3;</code> */ public int getValuesKeysCount() { return valuesKeys_.size(); } /** * <code>repeated string valuesKeys = 3;</code> */ public java.lang.String getValuesKeys(int index) { return valuesKeys_.get(index); } /** * <code>repeated string valuesKeys = 3;</code> */ public com.google.protobuf.ByteString getValuesKeysBytes(int index) { return valuesKeys_.getByteString(index); } /** * <code>repeated string valuesKeys = 3;</code> */ public Builder setValuesKeys( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureValuesKeysIsMutable(); valuesKeys_.set(index, value); onChanged(); return this; } /** * <code>repeated string valuesKeys = 3;</code> */ public Builder addValuesKeys( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureValuesKeysIsMutable(); valuesKeys_.add(value); onChanged(); return this; } /** * <code>repeated string valuesKeys = 3;</code> */ public Builder addAllValuesKeys( java.lang.Iterable<java.lang.String> values) { ensureValuesKeysIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, valuesKeys_); onChanged(); return this; } /** * <code>repeated string valuesKeys = 3;</code> */ public Builder clearValuesKeys() { valuesKeys_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <code>repeated string valuesKeys = 3;</code> */ public Builder addValuesKeysBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureValuesKeysIsMutable(); valuesKeys_.add(value); onChanged(); return this; } private java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> valuesValues_ = java.util.Collections.emptyList(); private void ensureValuesValuesIsMutable() { if (!((bitField0_ & 0x00000008) == 0x00000008)) { valuesValues_ = new java.util.ArrayList<ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner>(valuesValues_); bitField0_ |= 0x00000008; } } private com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwnerOrBuilder> valuesValuesBuilder_; /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> getValuesValuesList() { if (valuesValuesBuilder_ == null) { return java.util.Collections.unmodifiableList(valuesValues_); } else { return valuesValuesBuilder_.getMessageList(); } } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public int getValuesValuesCount() { if (valuesValuesBuilder_ == null) { return valuesValues_.size(); } else { return valuesValuesBuilder_.getCount(); } } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getValuesValues(int index) { if (valuesValuesBuilder_ == null) { return valuesValues_.get(index); } else { return valuesValuesBuilder_.getMessage(index); } } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public Builder setValuesValues( int index, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner value) { if (valuesValuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureValuesValuesIsMutable(); valuesValues_.set(index, value); onChanged(); } else { valuesValuesBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public Builder setValuesValues( int index, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder builderForValue) { if (valuesValuesBuilder_ == null) { ensureValuesValuesIsMutable(); valuesValues_.set(index, builderForValue.build()); onChanged(); } else { valuesValuesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public Builder addValuesValues(ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner value) { if (valuesValuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureValuesValuesIsMutable(); valuesValues_.add(value); onChanged(); } else { valuesValuesBuilder_.addMessage(value); } return this; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public Builder addValuesValues( int index, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner value) { if (valuesValuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureValuesValuesIsMutable(); valuesValues_.add(index, value); onChanged(); } else { valuesValuesBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public Builder addValuesValues( ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder builderForValue) { if (valuesValuesBuilder_ == null) { ensureValuesValuesIsMutable(); valuesValues_.add(builderForValue.build()); onChanged(); } else { valuesValuesBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public Builder addValuesValues( int index, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder builderForValue) { if (valuesValuesBuilder_ == null) { ensureValuesValuesIsMutable(); valuesValues_.add(index, builderForValue.build()); onChanged(); } else { valuesValuesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public Builder addAllValuesValues( java.lang.Iterable<? extends ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner> values) { if (valuesValuesBuilder_ == null) { ensureValuesValuesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, valuesValues_); onChanged(); } else { valuesValuesBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public Builder clearValuesValues() { if (valuesValuesBuilder_ == null) { valuesValues_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); } else { valuesValuesBuilder_.clear(); } return this; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public Builder removeValuesValues(int index) { if (valuesValuesBuilder_ == null) { ensureValuesValuesIsMutable(); valuesValues_.remove(index); onChanged(); } else { valuesValuesBuilder_.remove(index); } return this; } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder getValuesValuesBuilder( int index) { return getValuesValuesFieldBuilder().getBuilder(index); } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwnerOrBuilder getValuesValuesOrBuilder( int index) { if (valuesValuesBuilder_ == null) { return valuesValues_.get(index); } else { return valuesValuesBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwnerOrBuilder> getValuesValuesOrBuilderList() { if (valuesValuesBuilder_ != null) { return valuesValuesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(valuesValues_); } } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder addValuesValuesBuilder() { return getValuesValuesFieldBuilder().addBuilder( ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.getDefaultInstance()); } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder addValuesValuesBuilder( int index) { return getValuesValuesFieldBuilder().addBuilder( index, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.getDefaultInstance()); } /** * <code>repeated .ai.eloquent.raft.ValueWithOptionalOwner valuesValues = 4;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder> getValuesValuesBuilderList() { return getValuesValuesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwnerOrBuilder> getValuesValuesFieldBuilder() { if (valuesValuesBuilder_ == null) { valuesValuesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwnerOrBuilder>( valuesValues_, ((bitField0_ & 0x00000008) == 0x00000008), getParentForChildren(), isClean()); valuesValues_ = null; } return valuesValuesBuilder_; } private com.google.protobuf.LazyStringList locksKeys_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureLocksKeysIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { locksKeys_ = new com.google.protobuf.LazyStringArrayList(locksKeys_); bitField0_ |= 0x00000010; } } /** * <code>repeated string locksKeys = 5;</code> */ public com.google.protobuf.ProtocolStringList getLocksKeysList() { return locksKeys_.getUnmodifiableView(); } /** * <code>repeated string locksKeys = 5;</code> */ public int getLocksKeysCount() { return locksKeys_.size(); } /** * <code>repeated string locksKeys = 5;</code> */ public java.lang.String getLocksKeys(int index) { return locksKeys_.get(index); } /** * <code>repeated string locksKeys = 5;</code> */ public com.google.protobuf.ByteString getLocksKeysBytes(int index) { return locksKeys_.getByteString(index); } /** * <code>repeated string locksKeys = 5;</code> */ public Builder setLocksKeys( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureLocksKeysIsMutable(); locksKeys_.set(index, value); onChanged(); return this; } /** * <code>repeated string locksKeys = 5;</code> */ public Builder addLocksKeys( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureLocksKeysIsMutable(); locksKeys_.add(value); onChanged(); return this; } /** * <code>repeated string locksKeys = 5;</code> */ public Builder addAllLocksKeys( java.lang.Iterable<java.lang.String> values) { ensureLocksKeysIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, locksKeys_); onChanged(); return this; } /** * <code>repeated string locksKeys = 5;</code> */ public Builder clearLocksKeys() { locksKeys_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** * <code>repeated string locksKeys = 5;</code> */ public Builder addLocksKeysBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureLocksKeysIsMutable(); locksKeys_.add(value); onChanged(); return this; } private java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> locksValues_ = java.util.Collections.emptyList(); private void ensureLocksValuesIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { locksValues_ = new java.util.ArrayList<ai.eloquent.raft.KeyValueStateMachineProto.QueueLock>(locksValues_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.QueueLock, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.QueueLockOrBuilder> locksValuesBuilder_; /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> getLocksValuesList() { if (locksValuesBuilder_ == null) { return java.util.Collections.unmodifiableList(locksValues_); } else { return locksValuesBuilder_.getMessageList(); } } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public int getLocksValuesCount() { if (locksValuesBuilder_ == null) { return locksValues_.size(); } else { return locksValuesBuilder_.getCount(); } } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getLocksValues(int index) { if (locksValuesBuilder_ == null) { return locksValues_.get(index); } else { return locksValuesBuilder_.getMessage(index); } } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public Builder setLocksValues( int index, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock value) { if (locksValuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLocksValuesIsMutable(); locksValues_.set(index, value); onChanged(); } else { locksValuesBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public Builder setLocksValues( int index, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder builderForValue) { if (locksValuesBuilder_ == null) { ensureLocksValuesIsMutable(); locksValues_.set(index, builderForValue.build()); onChanged(); } else { locksValuesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public Builder addLocksValues(ai.eloquent.raft.KeyValueStateMachineProto.QueueLock value) { if (locksValuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLocksValuesIsMutable(); locksValues_.add(value); onChanged(); } else { locksValuesBuilder_.addMessage(value); } return this; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public Builder addLocksValues( int index, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock value) { if (locksValuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLocksValuesIsMutable(); locksValues_.add(index, value); onChanged(); } else { locksValuesBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public Builder addLocksValues( ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder builderForValue) { if (locksValuesBuilder_ == null) { ensureLocksValuesIsMutable(); locksValues_.add(builderForValue.build()); onChanged(); } else { locksValuesBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public Builder addLocksValues( int index, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder builderForValue) { if (locksValuesBuilder_ == null) { ensureLocksValuesIsMutable(); locksValues_.add(index, builderForValue.build()); onChanged(); } else { locksValuesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public Builder addAllLocksValues( java.lang.Iterable<? extends ai.eloquent.raft.KeyValueStateMachineProto.QueueLock> values) { if (locksValuesBuilder_ == null) { ensureLocksValuesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, locksValues_); onChanged(); } else { locksValuesBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public Builder clearLocksValues() { if (locksValuesBuilder_ == null) { locksValues_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { locksValuesBuilder_.clear(); } return this; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public Builder removeLocksValues(int index) { if (locksValuesBuilder_ == null) { ensureLocksValuesIsMutable(); locksValues_.remove(index); onChanged(); } else { locksValuesBuilder_.remove(index); } return this; } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder getLocksValuesBuilder( int index) { return getLocksValuesFieldBuilder().getBuilder(index); } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLockOrBuilder getLocksValuesOrBuilder( int index) { if (locksValuesBuilder_ == null) { return locksValues_.get(index); } else { return locksValuesBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.QueueLockOrBuilder> getLocksValuesOrBuilderList() { if (locksValuesBuilder_ != null) { return locksValuesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(locksValues_); } } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder addLocksValuesBuilder() { return getLocksValuesFieldBuilder().addBuilder( ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.getDefaultInstance()); } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder addLocksValuesBuilder( int index) { return getLocksValuesFieldBuilder().addBuilder( index, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.getDefaultInstance()); } /** * <code>repeated .ai.eloquent.raft.QueueLock locksValues = 6;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder> getLocksValuesBuilderList() { return getLocksValuesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.QueueLock, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.QueueLockOrBuilder> getLocksValuesFieldBuilder() { if (locksValuesBuilder_ == null) { locksValuesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.QueueLock, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.QueueLockOrBuilder>( locksValues_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); locksValues_ = null; } return locksValuesBuilder_; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.KVStateMachine) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.KVStateMachine) private static final ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine(); } public static ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<KVStateMachine> PARSER = new com.google.protobuf.AbstractParser<KVStateMachine>() { public KVStateMachine parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new KVStateMachine(input, extensionRegistry); } }; public static com.google.protobuf.Parser<KVStateMachine> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<KVStateMachine> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.KVStateMachine getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ValueWithOptionalOwnerOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.ValueWithOptionalOwner) com.google.protobuf.MessageOrBuilder { /** * <code>bytes value = 1;</code> */ com.google.protobuf.ByteString getValue(); /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 2;</code> */ java.lang.String getOwner(); /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 2;</code> */ com.google.protobuf.ByteString getOwnerBytes(); /** * <code>uint64 last_accessed = 3;</code> */ long getLastAccessed(); /** * <code>uint64 created_at = 4;</code> */ long getCreatedAt(); } /** * Protobuf type {@code ai.eloquent.raft.ValueWithOptionalOwner} */ public static final class ValueWithOptionalOwner extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.ValueWithOptionalOwner) ValueWithOptionalOwnerOrBuilder { private static final long serialVersionUID = 0L; // Use ValueWithOptionalOwner.newBuilder() to construct. private ValueWithOptionalOwner(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ValueWithOptionalOwner() { value_ = com.google.protobuf.ByteString.EMPTY; owner_ = ""; lastAccessed_ = 0L; createdAt_ = 0L; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ValueWithOptionalOwner( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { value_ = input.readBytes(); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); owner_ = s; break; } case 24: { lastAccessed_ = input.readUInt64(); break; } case 32: { createdAt_ = input.readUInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ValueWithOptionalOwner_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ValueWithOptionalOwner_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.class, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder.class); } public static final int VALUE_FIELD_NUMBER = 1; private com.google.protobuf.ByteString value_; /** * <code>bytes value = 1;</code> */ public com.google.protobuf.ByteString getValue() { return value_; } public static final int OWNER_FIELD_NUMBER = 2; private volatile java.lang.Object owner_; /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 2;</code> */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } } /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 2;</code> */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LAST_ACCESSED_FIELD_NUMBER = 3; private long lastAccessed_; /** * <code>uint64 last_accessed = 3;</code> */ public long getLastAccessed() { return lastAccessed_; } public static final int CREATED_AT_FIELD_NUMBER = 4; private long createdAt_; /** * <code>uint64 created_at = 4;</code> */ public long getCreatedAt() { return createdAt_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!value_.isEmpty()) { output.writeBytes(1, value_); } if (!getOwnerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, owner_); } if (lastAccessed_ != 0L) { output.writeUInt64(3, lastAccessed_); } if (createdAt_ != 0L) { output.writeUInt64(4, createdAt_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!value_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, value_); } if (!getOwnerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, owner_); } if (lastAccessed_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(3, lastAccessed_); } if (createdAt_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, createdAt_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner other = (ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner) obj; boolean result = true; result = result && getValue() .equals(other.getValue()); result = result && getOwner() .equals(other.getOwner()); result = result && (getLastAccessed() == other.getLastAccessed()); result = result && (getCreatedAt() == other.getCreatedAt()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + VALUE_FIELD_NUMBER; hash = (53 * hash) + getValue().hashCode(); hash = (37 * hash) + OWNER_FIELD_NUMBER; hash = (53 * hash) + getOwner().hashCode(); hash = (37 * hash) + LAST_ACCESSED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getLastAccessed()); hash = (37 * hash) + CREATED_AT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getCreatedAt()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.ValueWithOptionalOwner} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.ValueWithOptionalOwner) ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwnerOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ValueWithOptionalOwner_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ValueWithOptionalOwner_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.class, ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); value_ = com.google.protobuf.ByteString.EMPTY; owner_ = ""; lastAccessed_ = 0L; createdAt_ = 0L; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ValueWithOptionalOwner_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner build() { ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner result = new ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner(this); result.value_ = value_; result.owner_ = owner_; result.lastAccessed_ = lastAccessed_; result.createdAt_ = createdAt_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner.getDefaultInstance()) return this; if (other.getValue() != com.google.protobuf.ByteString.EMPTY) { setValue(other.getValue()); } if (!other.getOwner().isEmpty()) { owner_ = other.owner_; onChanged(); } if (other.getLastAccessed() != 0L) { setLastAccessed(other.getLastAccessed()); } if (other.getCreatedAt() != 0L) { setCreatedAt(other.getCreatedAt()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private com.google.protobuf.ByteString value_ = com.google.protobuf.ByteString.EMPTY; /** * <code>bytes value = 1;</code> */ public com.google.protobuf.ByteString getValue() { return value_; } /** * <code>bytes value = 1;</code> */ public Builder setValue(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } value_ = value; onChanged(); return this; } /** * <code>bytes value = 1;</code> */ public Builder clearValue() { value_ = getDefaultInstance().getValue(); onChanged(); return this; } private java.lang.Object owner_ = ""; /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 2;</code> */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 2;</code> */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 2;</code> */ public Builder setOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } owner_ = value; onChanged(); return this; } /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 2;</code> */ public Builder clearOwner() { owner_ = getDefaultInstance().getOwner(); onChanged(); return this; } /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 2;</code> */ public Builder setOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); owner_ = value; onChanged(); return this; } private long lastAccessed_ ; /** * <code>uint64 last_accessed = 3;</code> */ public long getLastAccessed() { return lastAccessed_; } /** * <code>uint64 last_accessed = 3;</code> */ public Builder setLastAccessed(long value) { lastAccessed_ = value; onChanged(); return this; } /** * <code>uint64 last_accessed = 3;</code> */ public Builder clearLastAccessed() { lastAccessed_ = 0L; onChanged(); return this; } private long createdAt_ ; /** * <code>uint64 created_at = 4;</code> */ public long getCreatedAt() { return createdAt_; } /** * <code>uint64 created_at = 4;</code> */ public Builder setCreatedAt(long value) { createdAt_ = value; onChanged(); return this; } /** * <code>uint64 created_at = 4;</code> */ public Builder clearCreatedAt() { createdAt_ = 0L; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.ValueWithOptionalOwner) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.ValueWithOptionalOwner) private static final ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner(); } public static ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ValueWithOptionalOwner> PARSER = new com.google.protobuf.AbstractParser<ValueWithOptionalOwner>() { public ValueWithOptionalOwner parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ValueWithOptionalOwner(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ValueWithOptionalOwner> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ValueWithOptionalOwner> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.ValueWithOptionalOwner getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface QueueLockOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.QueueLock) com.google.protobuf.MessageOrBuilder { /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ boolean hasHolder(); /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.LockRequest getHolder(); /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder getHolderOrBuilder(); /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.LockRequest> getWaitingList(); /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.LockRequest getWaiting(int index); /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ int getWaitingCount(); /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder> getWaitingOrBuilderList(); /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder getWaitingOrBuilder( int index); } /** * Protobuf type {@code ai.eloquent.raft.QueueLock} */ public static final class QueueLock extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.QueueLock) QueueLockOrBuilder { private static final long serialVersionUID = 0L; // Use QueueLock.newBuilder() to construct. private QueueLock(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private QueueLock() { waiting_ = java.util.Collections.emptyList(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private QueueLock( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder subBuilder = null; if (holder_ != null) { subBuilder = holder_.toBuilder(); } holder_ = input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(holder_); holder_ = subBuilder.buildPartial(); } break; } case 18: { if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { waiting_ = new java.util.ArrayList<ai.eloquent.raft.KeyValueStateMachineProto.LockRequest>(); mutable_bitField0_ |= 0x00000002; } waiting_.add( input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.parser(), extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { waiting_ = java.util.Collections.unmodifiableList(waiting_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_QueueLock_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_QueueLock_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.class, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder.class); } private int bitField0_; public static final int HOLDER_FIELD_NUMBER = 1; private ai.eloquent.raft.KeyValueStateMachineProto.LockRequest holder_; /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public boolean hasHolder() { return holder_ != null; } /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest getHolder() { return holder_ == null ? ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.getDefaultInstance() : holder_; } /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder getHolderOrBuilder() { return getHolder(); } public static final int WAITING_FIELD_NUMBER = 2; private java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.LockRequest> waiting_; /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.LockRequest> getWaitingList() { return waiting_; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder> getWaitingOrBuilderList() { return waiting_; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public int getWaitingCount() { return waiting_.size(); } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest getWaiting(int index) { return waiting_.get(index); } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder getWaitingOrBuilder( int index) { return waiting_.get(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (holder_ != null) { output.writeMessage(1, getHolder()); } for (int i = 0; i < waiting_.size(); i++) { output.writeMessage(2, waiting_.get(i)); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (holder_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, getHolder()); } for (int i = 0; i < waiting_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, waiting_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.QueueLock)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.QueueLock other = (ai.eloquent.raft.KeyValueStateMachineProto.QueueLock) obj; boolean result = true; result = result && (hasHolder() == other.hasHolder()); if (hasHolder()) { result = result && getHolder() .equals(other.getHolder()); } result = result && getWaitingList() .equals(other.getWaitingList()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasHolder()) { hash = (37 * hash) + HOLDER_FIELD_NUMBER; hash = (53 * hash) + getHolder().hashCode(); } if (getWaitingCount() > 0) { hash = (37 * hash) + WAITING_FIELD_NUMBER; hash = (53 * hash) + getWaitingList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.QueueLock prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.QueueLock} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.QueueLock) ai.eloquent.raft.KeyValueStateMachineProto.QueueLockOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_QueueLock_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_QueueLock_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.class, ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getWaitingFieldBuilder(); } } public Builder clear() { super.clear(); if (holderBuilder_ == null) { holder_ = null; } else { holder_ = null; holderBuilder_ = null; } if (waitingBuilder_ == null) { waiting_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); } else { waitingBuilder_.clear(); } return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_QueueLock_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock build() { ai.eloquent.raft.KeyValueStateMachineProto.QueueLock result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.QueueLock result = new ai.eloquent.raft.KeyValueStateMachineProto.QueueLock(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (holderBuilder_ == null) { result.holder_ = holder_; } else { result.holder_ = holderBuilder_.build(); } if (waitingBuilder_ == null) { if (((bitField0_ & 0x00000002) == 0x00000002)) { waiting_ = java.util.Collections.unmodifiableList(waiting_); bitField0_ = (bitField0_ & ~0x00000002); } result.waiting_ = waiting_; } else { result.waiting_ = waitingBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.QueueLock) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.QueueLock)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.QueueLock other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.QueueLock.getDefaultInstance()) return this; if (other.hasHolder()) { mergeHolder(other.getHolder()); } if (waitingBuilder_ == null) { if (!other.waiting_.isEmpty()) { if (waiting_.isEmpty()) { waiting_ = other.waiting_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureWaitingIsMutable(); waiting_.addAll(other.waiting_); } onChanged(); } } else { if (!other.waiting_.isEmpty()) { if (waitingBuilder_.isEmpty()) { waitingBuilder_.dispose(); waitingBuilder_ = null; waiting_ = other.waiting_; bitField0_ = (bitField0_ & ~0x00000002); waitingBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getWaitingFieldBuilder() : null; } else { waitingBuilder_.addAllMessages(other.waiting_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.QueueLock parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.QueueLock) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private ai.eloquent.raft.KeyValueStateMachineProto.LockRequest holder_ = null; private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.LockRequest, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder, ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder> holderBuilder_; /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public boolean hasHolder() { return holderBuilder_ != null || holder_ != null; } /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest getHolder() { if (holderBuilder_ == null) { return holder_ == null ? ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.getDefaultInstance() : holder_; } else { return holderBuilder_.getMessage(); } } /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public Builder setHolder(ai.eloquent.raft.KeyValueStateMachineProto.LockRequest value) { if (holderBuilder_ == null) { if (value == null) { throw new NullPointerException(); } holder_ = value; onChanged(); } else { holderBuilder_.setMessage(value); } return this; } /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public Builder setHolder( ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder builderForValue) { if (holderBuilder_ == null) { holder_ = builderForValue.build(); onChanged(); } else { holderBuilder_.setMessage(builderForValue.build()); } return this; } /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public Builder mergeHolder(ai.eloquent.raft.KeyValueStateMachineProto.LockRequest value) { if (holderBuilder_ == null) { if (holder_ != null) { holder_ = ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.newBuilder(holder_).mergeFrom(value).buildPartial(); } else { holder_ = value; } onChanged(); } else { holderBuilder_.mergeFrom(value); } return this; } /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public Builder clearHolder() { if (holderBuilder_ == null) { holder_ = null; onChanged(); } else { holder_ = null; holderBuilder_ = null; } return this; } /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder getHolderBuilder() { onChanged(); return getHolderFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder getHolderOrBuilder() { if (holderBuilder_ != null) { return holderBuilder_.getMessageOrBuilder(); } else { return holder_ == null ? ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.getDefaultInstance() : holder_; } } /** * <code>.ai.eloquent.raft.LockRequest holder = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.LockRequest, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder, ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder> getHolderFieldBuilder() { if (holderBuilder_ == null) { holderBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.LockRequest, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder, ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder>( getHolder(), getParentForChildren(), isClean()); holder_ = null; } return holderBuilder_; } private java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.LockRequest> waiting_ = java.util.Collections.emptyList(); private void ensureWaitingIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { waiting_ = new java.util.ArrayList<ai.eloquent.raft.KeyValueStateMachineProto.LockRequest>(waiting_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.LockRequest, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder, ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder> waitingBuilder_; /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.LockRequest> getWaitingList() { if (waitingBuilder_ == null) { return java.util.Collections.unmodifiableList(waiting_); } else { return waitingBuilder_.getMessageList(); } } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public int getWaitingCount() { if (waitingBuilder_ == null) { return waiting_.size(); } else { return waitingBuilder_.getCount(); } } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest getWaiting(int index) { if (waitingBuilder_ == null) { return waiting_.get(index); } else { return waitingBuilder_.getMessage(index); } } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public Builder setWaiting( int index, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest value) { if (waitingBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureWaitingIsMutable(); waiting_.set(index, value); onChanged(); } else { waitingBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public Builder setWaiting( int index, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder builderForValue) { if (waitingBuilder_ == null) { ensureWaitingIsMutable(); waiting_.set(index, builderForValue.build()); onChanged(); } else { waitingBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public Builder addWaiting(ai.eloquent.raft.KeyValueStateMachineProto.LockRequest value) { if (waitingBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureWaitingIsMutable(); waiting_.add(value); onChanged(); } else { waitingBuilder_.addMessage(value); } return this; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public Builder addWaiting( int index, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest value) { if (waitingBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureWaitingIsMutable(); waiting_.add(index, value); onChanged(); } else { waitingBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public Builder addWaiting( ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder builderForValue) { if (waitingBuilder_ == null) { ensureWaitingIsMutable(); waiting_.add(builderForValue.build()); onChanged(); } else { waitingBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public Builder addWaiting( int index, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder builderForValue) { if (waitingBuilder_ == null) { ensureWaitingIsMutable(); waiting_.add(index, builderForValue.build()); onChanged(); } else { waitingBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public Builder addAllWaiting( java.lang.Iterable<? extends ai.eloquent.raft.KeyValueStateMachineProto.LockRequest> values) { if (waitingBuilder_ == null) { ensureWaitingIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, waiting_); onChanged(); } else { waitingBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public Builder clearWaiting() { if (waitingBuilder_ == null) { waiting_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { waitingBuilder_.clear(); } return this; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public Builder removeWaiting(int index) { if (waitingBuilder_ == null) { ensureWaitingIsMutable(); waiting_.remove(index); onChanged(); } else { waitingBuilder_.remove(index); } return this; } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder getWaitingBuilder( int index) { return getWaitingFieldBuilder().getBuilder(index); } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder getWaitingOrBuilder( int index) { if (waitingBuilder_ == null) { return waiting_.get(index); } else { return waitingBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder> getWaitingOrBuilderList() { if (waitingBuilder_ != null) { return waitingBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(waiting_); } } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder addWaitingBuilder() { return getWaitingFieldBuilder().addBuilder( ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.getDefaultInstance()); } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder addWaitingBuilder( int index) { return getWaitingFieldBuilder().addBuilder( index, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.getDefaultInstance()); } /** * <code>repeated .ai.eloquent.raft.LockRequest waiting = 2;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder> getWaitingBuilderList() { return getWaitingFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.LockRequest, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder, ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder> getWaitingFieldBuilder() { if (waitingBuilder_ == null) { waitingBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.LockRequest, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder, ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder>( waiting_, ((bitField0_ & 0x00000002) == 0x00000002), getParentForChildren(), isClean()); waiting_ = null; } return waitingBuilder_; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.QueueLock) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.QueueLock) private static final ai.eloquent.raft.KeyValueStateMachineProto.QueueLock DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.QueueLock(); } public static ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<QueueLock> PARSER = new com.google.protobuf.AbstractParser<QueueLock>() { public QueueLock parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new QueueLock(input, extensionRegistry); } }; public static com.google.protobuf.Parser<QueueLock> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<QueueLock> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.QueueLock getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface LockRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.LockRequest) com.google.protobuf.MessageOrBuilder { /** * <code>string server = 1;</code> */ java.lang.String getServer(); /** * <code>string server = 1;</code> */ com.google.protobuf.ByteString getServerBytes(); /** * <code>string uniqueHash = 2;</code> */ java.lang.String getUniqueHash(); /** * <code>string uniqueHash = 2;</code> */ com.google.protobuf.ByteString getUniqueHashBytes(); } /** * Protobuf type {@code ai.eloquent.raft.LockRequest} */ public static final class LockRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.LockRequest) LockRequestOrBuilder { private static final long serialVersionUID = 0L; // Use LockRequest.newBuilder() to construct. private LockRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private LockRequest() { server_ = ""; uniqueHash_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private LockRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); server_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); uniqueHash_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_LockRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_LockRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.class, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder.class); } public static final int SERVER_FIELD_NUMBER = 1; private volatile java.lang.Object server_; /** * <code>string server = 1;</code> */ public java.lang.String getServer() { java.lang.Object ref = server_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); server_ = s; return s; } } /** * <code>string server = 1;</code> */ public com.google.protobuf.ByteString getServerBytes() { java.lang.Object ref = server_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); server_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int UNIQUEHASH_FIELD_NUMBER = 2; private volatile java.lang.Object uniqueHash_; /** * <code>string uniqueHash = 2;</code> */ public java.lang.String getUniqueHash() { java.lang.Object ref = uniqueHash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uniqueHash_ = s; return s; } } /** * <code>string uniqueHash = 2;</code> */ public com.google.protobuf.ByteString getUniqueHashBytes() { java.lang.Object ref = uniqueHash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uniqueHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getServerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, server_); } if (!getUniqueHashBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, uniqueHash_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getServerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, server_); } if (!getUniqueHashBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, uniqueHash_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.LockRequest)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.LockRequest other = (ai.eloquent.raft.KeyValueStateMachineProto.LockRequest) obj; boolean result = true; result = result && getServer() .equals(other.getServer()); result = result && getUniqueHash() .equals(other.getUniqueHash()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SERVER_FIELD_NUMBER; hash = (53 * hash) + getServer().hashCode(); hash = (37 * hash) + UNIQUEHASH_FIELD_NUMBER; hash = (53 * hash) + getUniqueHash().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.LockRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.LockRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.LockRequest) ai.eloquent.raft.KeyValueStateMachineProto.LockRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_LockRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_LockRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.class, ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); server_ = ""; uniqueHash_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_LockRequest_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest build() { ai.eloquent.raft.KeyValueStateMachineProto.LockRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.LockRequest result = new ai.eloquent.raft.KeyValueStateMachineProto.LockRequest(this); result.server_ = server_; result.uniqueHash_ = uniqueHash_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.LockRequest) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.LockRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.LockRequest other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.LockRequest.getDefaultInstance()) return this; if (!other.getServer().isEmpty()) { server_ = other.server_; onChanged(); } if (!other.getUniqueHash().isEmpty()) { uniqueHash_ = other.uniqueHash_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.LockRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.LockRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object server_ = ""; /** * <code>string server = 1;</code> */ public java.lang.String getServer() { java.lang.Object ref = server_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); server_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string server = 1;</code> */ public com.google.protobuf.ByteString getServerBytes() { java.lang.Object ref = server_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); server_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string server = 1;</code> */ public Builder setServer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } server_ = value; onChanged(); return this; } /** * <code>string server = 1;</code> */ public Builder clearServer() { server_ = getDefaultInstance().getServer(); onChanged(); return this; } /** * <code>string server = 1;</code> */ public Builder setServerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); server_ = value; onChanged(); return this; } private java.lang.Object uniqueHash_ = ""; /** * <code>string uniqueHash = 2;</code> */ public java.lang.String getUniqueHash() { java.lang.Object ref = uniqueHash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uniqueHash_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string uniqueHash = 2;</code> */ public com.google.protobuf.ByteString getUniqueHashBytes() { java.lang.Object ref = uniqueHash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uniqueHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string uniqueHash = 2;</code> */ public Builder setUniqueHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } uniqueHash_ = value; onChanged(); return this; } /** * <code>string uniqueHash = 2;</code> */ public Builder clearUniqueHash() { uniqueHash_ = getDefaultInstance().getUniqueHash(); onChanged(); return this; } /** * <code>string uniqueHash = 2;</code> */ public Builder setUniqueHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); uniqueHash_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.LockRequest) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.LockRequest) private static final ai.eloquent.raft.KeyValueStateMachineProto.LockRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.LockRequest(); } public static ai.eloquent.raft.KeyValueStateMachineProto.LockRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<LockRequest> PARSER = new com.google.protobuf.AbstractParser<LockRequest>() { public LockRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new LockRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<LockRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<LockRequest> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.LockRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface TransitionOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.Transition) com.google.protobuf.MessageOrBuilder { /** * <code>.ai.eloquent.raft.TransitionType type = 1;</code> */ int getTypeValue(); /** * <code>.ai.eloquent.raft.TransitionType type = 1;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.TransitionType getType(); /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ boolean hasRequestLock(); /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.RequestLock getRequestLock(); /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.RequestLockOrBuilder getRequestLockOrBuilder(); /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ boolean hasTryLock(); /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.TryLock getTryLock(); /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.TryLockOrBuilder getTryLockOrBuilder(); /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ boolean hasReleaseLock(); /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock getReleaseLock(); /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLockOrBuilder getReleaseLockOrBuilder(); /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ boolean hasSetValue(); /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.SetValue getSetValue(); /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.SetValueOrBuilder getSetValueOrBuilder(); /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ boolean hasRemoveValue(); /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue getRemoveValue(); /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.RemoveValueOrBuilder getRemoveValueOrBuilder(); /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ boolean hasClearTransients(); /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients getClearTransients(); /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.ClearTransientsOrBuilder getClearTransientsOrBuilder(); /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.Transition> getTransitionsList(); /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.Transition getTransitions(int index); /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ int getTransitionsCount(); /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.TransitionOrBuilder> getTransitionsOrBuilderList(); /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ ai.eloquent.raft.KeyValueStateMachineProto.TransitionOrBuilder getTransitionsOrBuilder( int index); public ai.eloquent.raft.KeyValueStateMachineProto.Transition.BodyCase getBodyCase(); } /** * Protobuf type {@code ai.eloquent.raft.Transition} */ public static final class Transition extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.Transition) TransitionOrBuilder { private static final long serialVersionUID = 0L; // Use Transition.newBuilder() to construct. private Transition(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Transition() { type_ = 0; transitions_ = java.util.Collections.emptyList(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Transition( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { int rawValue = input.readEnum(); type_ = rawValue; break; } case 18: { ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.Builder subBuilder = null; if (bodyCase_ == 2) { subBuilder = ((ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) body_).toBuilder(); } body_ = input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) body_); body_ = subBuilder.buildPartial(); } bodyCase_ = 2; break; } case 26: { ai.eloquent.raft.KeyValueStateMachineProto.TryLock.Builder subBuilder = null; if (bodyCase_ == 3) { subBuilder = ((ai.eloquent.raft.KeyValueStateMachineProto.TryLock) body_).toBuilder(); } body_ = input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.TryLock.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.TryLock) body_); body_ = subBuilder.buildPartial(); } bodyCase_ = 3; break; } case 34: { ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.Builder subBuilder = null; if (bodyCase_ == 4) { subBuilder = ((ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) body_).toBuilder(); } body_ = input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) body_); body_ = subBuilder.buildPartial(); } bodyCase_ = 4; break; } case 42: { ai.eloquent.raft.KeyValueStateMachineProto.SetValue.Builder subBuilder = null; if (bodyCase_ == 5) { subBuilder = ((ai.eloquent.raft.KeyValueStateMachineProto.SetValue) body_).toBuilder(); } body_ = input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.SetValue.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.SetValue) body_); body_ = subBuilder.buildPartial(); } bodyCase_ = 5; break; } case 50: { ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.Builder subBuilder = null; if (bodyCase_ == 6) { subBuilder = ((ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) body_).toBuilder(); } body_ = input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) body_); body_ = subBuilder.buildPartial(); } bodyCase_ = 6; break; } case 58: { ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.Builder subBuilder = null; if (bodyCase_ == 7) { subBuilder = ((ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) body_).toBuilder(); } body_ = input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) body_); body_ = subBuilder.buildPartial(); } bodyCase_ = 7; break; } case 66: { if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) { transitions_ = new java.util.ArrayList<ai.eloquent.raft.KeyValueStateMachineProto.Transition>(); mutable_bitField0_ |= 0x00000080; } transitions_.add( input.readMessage(ai.eloquent.raft.KeyValueStateMachineProto.Transition.parser(), extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) { transitions_ = java.util.Collections.unmodifiableList(transitions_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_Transition_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_Transition_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.Transition.class, ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder.class); } private int bitField0_; private int bodyCase_ = 0; private java.lang.Object body_; public enum BodyCase implements com.google.protobuf.Internal.EnumLite { REQUESTLOCK(2), TRYLOCK(3), RELEASELOCK(4), SETVALUE(5), REMOVEVALUE(6), CLEARTRANSIENTS(7), BODY_NOT_SET(0); private final int value; private BodyCase(int value) { this.value = value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static BodyCase valueOf(int value) { return forNumber(value); } public static BodyCase forNumber(int value) { switch (value) { case 2: return REQUESTLOCK; case 3: return TRYLOCK; case 4: return RELEASELOCK; case 5: return SETVALUE; case 6: return REMOVEVALUE; case 7: return CLEARTRANSIENTS; case 0: return BODY_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public BodyCase getBodyCase() { return BodyCase.forNumber( bodyCase_); } public static final int TYPE_FIELD_NUMBER = 1; private int type_; /** * <code>.ai.eloquent.raft.TransitionType type = 1;</code> */ public int getTypeValue() { return type_; } /** * <code>.ai.eloquent.raft.TransitionType type = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.TransitionType getType() { ai.eloquent.raft.KeyValueStateMachineProto.TransitionType result = ai.eloquent.raft.KeyValueStateMachineProto.TransitionType.valueOf(type_); return result == null ? ai.eloquent.raft.KeyValueStateMachineProto.TransitionType.UNRECOGNIZED : result; } public static final int REQUESTLOCK_FIELD_NUMBER = 2; /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public boolean hasRequestLock() { return bodyCase_ == 2; } /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.RequestLock getRequestLock() { if (bodyCase_ == 2) { return (ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.RequestLockOrBuilder getRequestLockOrBuilder() { if (bodyCase_ == 2) { return (ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.getDefaultInstance(); } public static final int TRYLOCK_FIELD_NUMBER = 3; /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public boolean hasTryLock() { return bodyCase_ == 3; } /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.TryLock getTryLock() { if (bodyCase_ == 3) { return (ai.eloquent.raft.KeyValueStateMachineProto.TryLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.TryLock.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.TryLockOrBuilder getTryLockOrBuilder() { if (bodyCase_ == 3) { return (ai.eloquent.raft.KeyValueStateMachineProto.TryLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.TryLock.getDefaultInstance(); } public static final int RELEASELOCK_FIELD_NUMBER = 4; /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public boolean hasReleaseLock() { return bodyCase_ == 4; } /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock getReleaseLock() { if (bodyCase_ == 4) { return (ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLockOrBuilder getReleaseLockOrBuilder() { if (bodyCase_ == 4) { return (ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.getDefaultInstance(); } public static final int SETVALUE_FIELD_NUMBER = 5; /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public boolean hasSetValue() { return bodyCase_ == 5; } /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.SetValue getSetValue() { if (bodyCase_ == 5) { return (ai.eloquent.raft.KeyValueStateMachineProto.SetValue) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.SetValue.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.SetValueOrBuilder getSetValueOrBuilder() { if (bodyCase_ == 5) { return (ai.eloquent.raft.KeyValueStateMachineProto.SetValue) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.SetValue.getDefaultInstance(); } public static final int REMOVEVALUE_FIELD_NUMBER = 6; /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public boolean hasRemoveValue() { return bodyCase_ == 6; } /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue getRemoveValue() { if (bodyCase_ == 6) { return (ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.RemoveValueOrBuilder getRemoveValueOrBuilder() { if (bodyCase_ == 6) { return (ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.getDefaultInstance(); } public static final int CLEARTRANSIENTS_FIELD_NUMBER = 7; /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public boolean hasClearTransients() { return bodyCase_ == 7; } /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients getClearTransients() { if (bodyCase_ == 7) { return (ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.getDefaultInstance(); } /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ClearTransientsOrBuilder getClearTransientsOrBuilder() { if (bodyCase_ == 7) { return (ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.getDefaultInstance(); } public static final int TRANSITIONS_FIELD_NUMBER = 8; private java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.Transition> transitions_; /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.Transition> getTransitionsList() { return transitions_; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.TransitionOrBuilder> getTransitionsOrBuilderList() { return transitions_; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public int getTransitionsCount() { return transitions_.size(); } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.Transition getTransitions(int index) { return transitions_.get(index); } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.TransitionOrBuilder getTransitionsOrBuilder( int index) { return transitions_.get(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (type_ != ai.eloquent.raft.KeyValueStateMachineProto.TransitionType.INVALID.getNumber()) { output.writeEnum(1, type_); } if (bodyCase_ == 2) { output.writeMessage(2, (ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) body_); } if (bodyCase_ == 3) { output.writeMessage(3, (ai.eloquent.raft.KeyValueStateMachineProto.TryLock) body_); } if (bodyCase_ == 4) { output.writeMessage(4, (ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) body_); } if (bodyCase_ == 5) { output.writeMessage(5, (ai.eloquent.raft.KeyValueStateMachineProto.SetValue) body_); } if (bodyCase_ == 6) { output.writeMessage(6, (ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) body_); } if (bodyCase_ == 7) { output.writeMessage(7, (ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) body_); } for (int i = 0; i < transitions_.size(); i++) { output.writeMessage(8, transitions_.get(i)); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (type_ != ai.eloquent.raft.KeyValueStateMachineProto.TransitionType.INVALID.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, type_); } if (bodyCase_ == 2) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, (ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) body_); } if (bodyCase_ == 3) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, (ai.eloquent.raft.KeyValueStateMachineProto.TryLock) body_); } if (bodyCase_ == 4) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, (ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) body_); } if (bodyCase_ == 5) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, (ai.eloquent.raft.KeyValueStateMachineProto.SetValue) body_); } if (bodyCase_ == 6) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(6, (ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) body_); } if (bodyCase_ == 7) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(7, (ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) body_); } for (int i = 0; i < transitions_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(8, transitions_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.Transition)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.Transition other = (ai.eloquent.raft.KeyValueStateMachineProto.Transition) obj; boolean result = true; result = result && type_ == other.type_; result = result && getTransitionsList() .equals(other.getTransitionsList()); result = result && getBodyCase().equals( other.getBodyCase()); if (!result) return false; switch (bodyCase_) { case 2: result = result && getRequestLock() .equals(other.getRequestLock()); break; case 3: result = result && getTryLock() .equals(other.getTryLock()); break; case 4: result = result && getReleaseLock() .equals(other.getReleaseLock()); break; case 5: result = result && getSetValue() .equals(other.getSetValue()); break; case 6: result = result && getRemoveValue() .equals(other.getRemoveValue()); break; case 7: result = result && getClearTransients() .equals(other.getClearTransients()); break; case 0: default: } result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; if (getTransitionsCount() > 0) { hash = (37 * hash) + TRANSITIONS_FIELD_NUMBER; hash = (53 * hash) + getTransitionsList().hashCode(); } switch (bodyCase_) { case 2: hash = (37 * hash) + REQUESTLOCK_FIELD_NUMBER; hash = (53 * hash) + getRequestLock().hashCode(); break; case 3: hash = (37 * hash) + TRYLOCK_FIELD_NUMBER; hash = (53 * hash) + getTryLock().hashCode(); break; case 4: hash = (37 * hash) + RELEASELOCK_FIELD_NUMBER; hash = (53 * hash) + getReleaseLock().hashCode(); break; case 5: hash = (37 * hash) + SETVALUE_FIELD_NUMBER; hash = (53 * hash) + getSetValue().hashCode(); break; case 6: hash = (37 * hash) + REMOVEVALUE_FIELD_NUMBER; hash = (53 * hash) + getRemoveValue().hashCode(); break; case 7: hash = (37 * hash) + CLEARTRANSIENTS_FIELD_NUMBER; hash = (53 * hash) + getClearTransients().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.Transition prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.Transition} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.Transition) ai.eloquent.raft.KeyValueStateMachineProto.TransitionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_Transition_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_Transition_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.Transition.class, ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.Transition.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getTransitionsFieldBuilder(); } } public Builder clear() { super.clear(); type_ = 0; if (transitionsBuilder_ == null) { transitions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000080); } else { transitionsBuilder_.clear(); } bodyCase_ = 0; body_ = null; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_Transition_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.Transition getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.Transition.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.Transition build() { ai.eloquent.raft.KeyValueStateMachineProto.Transition result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.Transition buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.Transition result = new ai.eloquent.raft.KeyValueStateMachineProto.Transition(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.type_ = type_; if (bodyCase_ == 2) { if (requestLockBuilder_ == null) { result.body_ = body_; } else { result.body_ = requestLockBuilder_.build(); } } if (bodyCase_ == 3) { if (tryLockBuilder_ == null) { result.body_ = body_; } else { result.body_ = tryLockBuilder_.build(); } } if (bodyCase_ == 4) { if (releaseLockBuilder_ == null) { result.body_ = body_; } else { result.body_ = releaseLockBuilder_.build(); } } if (bodyCase_ == 5) { if (setValueBuilder_ == null) { result.body_ = body_; } else { result.body_ = setValueBuilder_.build(); } } if (bodyCase_ == 6) { if (removeValueBuilder_ == null) { result.body_ = body_; } else { result.body_ = removeValueBuilder_.build(); } } if (bodyCase_ == 7) { if (clearTransientsBuilder_ == null) { result.body_ = body_; } else { result.body_ = clearTransientsBuilder_.build(); } } if (transitionsBuilder_ == null) { if (((bitField0_ & 0x00000080) == 0x00000080)) { transitions_ = java.util.Collections.unmodifiableList(transitions_); bitField0_ = (bitField0_ & ~0x00000080); } result.transitions_ = transitions_; } else { result.transitions_ = transitionsBuilder_.build(); } result.bitField0_ = to_bitField0_; result.bodyCase_ = bodyCase_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.Transition) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.Transition)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.Transition other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.Transition.getDefaultInstance()) return this; if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } if (transitionsBuilder_ == null) { if (!other.transitions_.isEmpty()) { if (transitions_.isEmpty()) { transitions_ = other.transitions_; bitField0_ = (bitField0_ & ~0x00000080); } else { ensureTransitionsIsMutable(); transitions_.addAll(other.transitions_); } onChanged(); } } else { if (!other.transitions_.isEmpty()) { if (transitionsBuilder_.isEmpty()) { transitionsBuilder_.dispose(); transitionsBuilder_ = null; transitions_ = other.transitions_; bitField0_ = (bitField0_ & ~0x00000080); transitionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getTransitionsFieldBuilder() : null; } else { transitionsBuilder_.addAllMessages(other.transitions_); } } } switch (other.getBodyCase()) { case REQUESTLOCK: { mergeRequestLock(other.getRequestLock()); break; } case TRYLOCK: { mergeTryLock(other.getTryLock()); break; } case RELEASELOCK: { mergeReleaseLock(other.getReleaseLock()); break; } case SETVALUE: { mergeSetValue(other.getSetValue()); break; } case REMOVEVALUE: { mergeRemoveValue(other.getRemoveValue()); break; } case CLEARTRANSIENTS: { mergeClearTransients(other.getClearTransients()); break; } case BODY_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.Transition parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.Transition) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bodyCase_ = 0; private java.lang.Object body_; public BodyCase getBodyCase() { return BodyCase.forNumber( bodyCase_); } public Builder clearBody() { bodyCase_ = 0; body_ = null; onChanged(); return this; } private int bitField0_; private int type_ = 0; /** * <code>.ai.eloquent.raft.TransitionType type = 1;</code> */ public int getTypeValue() { return type_; } /** * <code>.ai.eloquent.raft.TransitionType type = 1;</code> */ public Builder setTypeValue(int value) { type_ = value; onChanged(); return this; } /** * <code>.ai.eloquent.raft.TransitionType type = 1;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.TransitionType getType() { ai.eloquent.raft.KeyValueStateMachineProto.TransitionType result = ai.eloquent.raft.KeyValueStateMachineProto.TransitionType.valueOf(type_); return result == null ? ai.eloquent.raft.KeyValueStateMachineProto.TransitionType.UNRECOGNIZED : result; } /** * <code>.ai.eloquent.raft.TransitionType type = 1;</code> */ public Builder setType(ai.eloquent.raft.KeyValueStateMachineProto.TransitionType value) { if (value == null) { throw new NullPointerException(); } type_ = value.getNumber(); onChanged(); return this; } /** * <code>.ai.eloquent.raft.TransitionType type = 1;</code> */ public Builder clearType() { type_ = 0; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.RequestLock, ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.RequestLockOrBuilder> requestLockBuilder_; /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public boolean hasRequestLock() { return bodyCase_ == 2; } /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.RequestLock getRequestLock() { if (requestLockBuilder_ == null) { if (bodyCase_ == 2) { return (ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.getDefaultInstance(); } else { if (bodyCase_ == 2) { return requestLockBuilder_.getMessage(); } return ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public Builder setRequestLock(ai.eloquent.raft.KeyValueStateMachineProto.RequestLock value) { if (requestLockBuilder_ == null) { if (value == null) { throw new NullPointerException(); } body_ = value; onChanged(); } else { requestLockBuilder_.setMessage(value); } bodyCase_ = 2; return this; } /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public Builder setRequestLock( ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.Builder builderForValue) { if (requestLockBuilder_ == null) { body_ = builderForValue.build(); onChanged(); } else { requestLockBuilder_.setMessage(builderForValue.build()); } bodyCase_ = 2; return this; } /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public Builder mergeRequestLock(ai.eloquent.raft.KeyValueStateMachineProto.RequestLock value) { if (requestLockBuilder_ == null) { if (bodyCase_ == 2 && body_ != ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.getDefaultInstance()) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.newBuilder((ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) body_) .mergeFrom(value).buildPartial(); } else { body_ = value; } onChanged(); } else { if (bodyCase_ == 2) { requestLockBuilder_.mergeFrom(value); } requestLockBuilder_.setMessage(value); } bodyCase_ = 2; return this; } /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public Builder clearRequestLock() { if (requestLockBuilder_ == null) { if (bodyCase_ == 2) { bodyCase_ = 0; body_ = null; onChanged(); } } else { if (bodyCase_ == 2) { bodyCase_ = 0; body_ = null; } requestLockBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.Builder getRequestLockBuilder() { return getRequestLockFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.RequestLockOrBuilder getRequestLockOrBuilder() { if ((bodyCase_ == 2) && (requestLockBuilder_ != null)) { return requestLockBuilder_.getMessageOrBuilder(); } else { if (bodyCase_ == 2) { return (ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RequestLock requestLock = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.RequestLock, ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.RequestLockOrBuilder> getRequestLockFieldBuilder() { if (requestLockBuilder_ == null) { if (!(bodyCase_ == 2)) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.getDefaultInstance(); } requestLockBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.RequestLock, ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.RequestLockOrBuilder>( (ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) body_, getParentForChildren(), isClean()); body_ = null; } bodyCase_ = 2; onChanged();; return requestLockBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.TryLock, ai.eloquent.raft.KeyValueStateMachineProto.TryLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.TryLockOrBuilder> tryLockBuilder_; /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public boolean hasTryLock() { return bodyCase_ == 3; } /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.TryLock getTryLock() { if (tryLockBuilder_ == null) { if (bodyCase_ == 3) { return (ai.eloquent.raft.KeyValueStateMachineProto.TryLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.TryLock.getDefaultInstance(); } else { if (bodyCase_ == 3) { return tryLockBuilder_.getMessage(); } return ai.eloquent.raft.KeyValueStateMachineProto.TryLock.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public Builder setTryLock(ai.eloquent.raft.KeyValueStateMachineProto.TryLock value) { if (tryLockBuilder_ == null) { if (value == null) { throw new NullPointerException(); } body_ = value; onChanged(); } else { tryLockBuilder_.setMessage(value); } bodyCase_ = 3; return this; } /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public Builder setTryLock( ai.eloquent.raft.KeyValueStateMachineProto.TryLock.Builder builderForValue) { if (tryLockBuilder_ == null) { body_ = builderForValue.build(); onChanged(); } else { tryLockBuilder_.setMessage(builderForValue.build()); } bodyCase_ = 3; return this; } /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public Builder mergeTryLock(ai.eloquent.raft.KeyValueStateMachineProto.TryLock value) { if (tryLockBuilder_ == null) { if (bodyCase_ == 3 && body_ != ai.eloquent.raft.KeyValueStateMachineProto.TryLock.getDefaultInstance()) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.TryLock.newBuilder((ai.eloquent.raft.KeyValueStateMachineProto.TryLock) body_) .mergeFrom(value).buildPartial(); } else { body_ = value; } onChanged(); } else { if (bodyCase_ == 3) { tryLockBuilder_.mergeFrom(value); } tryLockBuilder_.setMessage(value); } bodyCase_ = 3; return this; } /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public Builder clearTryLock() { if (tryLockBuilder_ == null) { if (bodyCase_ == 3) { bodyCase_ = 0; body_ = null; onChanged(); } } else { if (bodyCase_ == 3) { bodyCase_ = 0; body_ = null; } tryLockBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.TryLock.Builder getTryLockBuilder() { return getTryLockFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.TryLockOrBuilder getTryLockOrBuilder() { if ((bodyCase_ == 3) && (tryLockBuilder_ != null)) { return tryLockBuilder_.getMessageOrBuilder(); } else { if (bodyCase_ == 3) { return (ai.eloquent.raft.KeyValueStateMachineProto.TryLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.TryLock.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.TryLock tryLock = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.TryLock, ai.eloquent.raft.KeyValueStateMachineProto.TryLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.TryLockOrBuilder> getTryLockFieldBuilder() { if (tryLockBuilder_ == null) { if (!(bodyCase_ == 3)) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.TryLock.getDefaultInstance(); } tryLockBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.TryLock, ai.eloquent.raft.KeyValueStateMachineProto.TryLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.TryLockOrBuilder>( (ai.eloquent.raft.KeyValueStateMachineProto.TryLock) body_, getParentForChildren(), isClean()); body_ = null; } bodyCase_ = 3; onChanged();; return tryLockBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock, ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLockOrBuilder> releaseLockBuilder_; /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public boolean hasReleaseLock() { return bodyCase_ == 4; } /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock getReleaseLock() { if (releaseLockBuilder_ == null) { if (bodyCase_ == 4) { return (ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.getDefaultInstance(); } else { if (bodyCase_ == 4) { return releaseLockBuilder_.getMessage(); } return ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public Builder setReleaseLock(ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock value) { if (releaseLockBuilder_ == null) { if (value == null) { throw new NullPointerException(); } body_ = value; onChanged(); } else { releaseLockBuilder_.setMessage(value); } bodyCase_ = 4; return this; } /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public Builder setReleaseLock( ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.Builder builderForValue) { if (releaseLockBuilder_ == null) { body_ = builderForValue.build(); onChanged(); } else { releaseLockBuilder_.setMessage(builderForValue.build()); } bodyCase_ = 4; return this; } /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public Builder mergeReleaseLock(ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock value) { if (releaseLockBuilder_ == null) { if (bodyCase_ == 4 && body_ != ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.getDefaultInstance()) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.newBuilder((ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) body_) .mergeFrom(value).buildPartial(); } else { body_ = value; } onChanged(); } else { if (bodyCase_ == 4) { releaseLockBuilder_.mergeFrom(value); } releaseLockBuilder_.setMessage(value); } bodyCase_ = 4; return this; } /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public Builder clearReleaseLock() { if (releaseLockBuilder_ == null) { if (bodyCase_ == 4) { bodyCase_ = 0; body_ = null; onChanged(); } } else { if (bodyCase_ == 4) { bodyCase_ = 0; body_ = null; } releaseLockBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.Builder getReleaseLockBuilder() { return getReleaseLockFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLockOrBuilder getReleaseLockOrBuilder() { if ((bodyCase_ == 4) && (releaseLockBuilder_ != null)) { return releaseLockBuilder_.getMessageOrBuilder(); } else { if (bodyCase_ == 4) { return (ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.ReleaseLock releaseLock = 4;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock, ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLockOrBuilder> getReleaseLockFieldBuilder() { if (releaseLockBuilder_ == null) { if (!(bodyCase_ == 4)) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.getDefaultInstance(); } releaseLockBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock, ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.Builder, ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLockOrBuilder>( (ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) body_, getParentForChildren(), isClean()); body_ = null; } bodyCase_ = 4; onChanged();; return releaseLockBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.SetValue, ai.eloquent.raft.KeyValueStateMachineProto.SetValue.Builder, ai.eloquent.raft.KeyValueStateMachineProto.SetValueOrBuilder> setValueBuilder_; /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public boolean hasSetValue() { return bodyCase_ == 5; } /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.SetValue getSetValue() { if (setValueBuilder_ == null) { if (bodyCase_ == 5) { return (ai.eloquent.raft.KeyValueStateMachineProto.SetValue) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.SetValue.getDefaultInstance(); } else { if (bodyCase_ == 5) { return setValueBuilder_.getMessage(); } return ai.eloquent.raft.KeyValueStateMachineProto.SetValue.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public Builder setSetValue(ai.eloquent.raft.KeyValueStateMachineProto.SetValue value) { if (setValueBuilder_ == null) { if (value == null) { throw new NullPointerException(); } body_ = value; onChanged(); } else { setValueBuilder_.setMessage(value); } bodyCase_ = 5; return this; } /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public Builder setSetValue( ai.eloquent.raft.KeyValueStateMachineProto.SetValue.Builder builderForValue) { if (setValueBuilder_ == null) { body_ = builderForValue.build(); onChanged(); } else { setValueBuilder_.setMessage(builderForValue.build()); } bodyCase_ = 5; return this; } /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public Builder mergeSetValue(ai.eloquent.raft.KeyValueStateMachineProto.SetValue value) { if (setValueBuilder_ == null) { if (bodyCase_ == 5 && body_ != ai.eloquent.raft.KeyValueStateMachineProto.SetValue.getDefaultInstance()) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.SetValue.newBuilder((ai.eloquent.raft.KeyValueStateMachineProto.SetValue) body_) .mergeFrom(value).buildPartial(); } else { body_ = value; } onChanged(); } else { if (bodyCase_ == 5) { setValueBuilder_.mergeFrom(value); } setValueBuilder_.setMessage(value); } bodyCase_ = 5; return this; } /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public Builder clearSetValue() { if (setValueBuilder_ == null) { if (bodyCase_ == 5) { bodyCase_ = 0; body_ = null; onChanged(); } } else { if (bodyCase_ == 5) { bodyCase_ = 0; body_ = null; } setValueBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.SetValue.Builder getSetValueBuilder() { return getSetValueFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.SetValueOrBuilder getSetValueOrBuilder() { if ((bodyCase_ == 5) && (setValueBuilder_ != null)) { return setValueBuilder_.getMessageOrBuilder(); } else { if (bodyCase_ == 5) { return (ai.eloquent.raft.KeyValueStateMachineProto.SetValue) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.SetValue.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.SetValue setValue = 5;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.SetValue, ai.eloquent.raft.KeyValueStateMachineProto.SetValue.Builder, ai.eloquent.raft.KeyValueStateMachineProto.SetValueOrBuilder> getSetValueFieldBuilder() { if (setValueBuilder_ == null) { if (!(bodyCase_ == 5)) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.SetValue.getDefaultInstance(); } setValueBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.SetValue, ai.eloquent.raft.KeyValueStateMachineProto.SetValue.Builder, ai.eloquent.raft.KeyValueStateMachineProto.SetValueOrBuilder>( (ai.eloquent.raft.KeyValueStateMachineProto.SetValue) body_, getParentForChildren(), isClean()); body_ = null; } bodyCase_ = 5; onChanged();; return setValueBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue, ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.Builder, ai.eloquent.raft.KeyValueStateMachineProto.RemoveValueOrBuilder> removeValueBuilder_; /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public boolean hasRemoveValue() { return bodyCase_ == 6; } /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue getRemoveValue() { if (removeValueBuilder_ == null) { if (bodyCase_ == 6) { return (ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.getDefaultInstance(); } else { if (bodyCase_ == 6) { return removeValueBuilder_.getMessage(); } return ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public Builder setRemoveValue(ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue value) { if (removeValueBuilder_ == null) { if (value == null) { throw new NullPointerException(); } body_ = value; onChanged(); } else { removeValueBuilder_.setMessage(value); } bodyCase_ = 6; return this; } /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public Builder setRemoveValue( ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.Builder builderForValue) { if (removeValueBuilder_ == null) { body_ = builderForValue.build(); onChanged(); } else { removeValueBuilder_.setMessage(builderForValue.build()); } bodyCase_ = 6; return this; } /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public Builder mergeRemoveValue(ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue value) { if (removeValueBuilder_ == null) { if (bodyCase_ == 6 && body_ != ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.getDefaultInstance()) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.newBuilder((ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) body_) .mergeFrom(value).buildPartial(); } else { body_ = value; } onChanged(); } else { if (bodyCase_ == 6) { removeValueBuilder_.mergeFrom(value); } removeValueBuilder_.setMessage(value); } bodyCase_ = 6; return this; } /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public Builder clearRemoveValue() { if (removeValueBuilder_ == null) { if (bodyCase_ == 6) { bodyCase_ = 0; body_ = null; onChanged(); } } else { if (bodyCase_ == 6) { bodyCase_ = 0; body_ = null; } removeValueBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.Builder getRemoveValueBuilder() { return getRemoveValueFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.RemoveValueOrBuilder getRemoveValueOrBuilder() { if ((bodyCase_ == 6) && (removeValueBuilder_ != null)) { return removeValueBuilder_.getMessageOrBuilder(); } else { if (bodyCase_ == 6) { return (ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.RemoveValue removeValue = 6;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue, ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.Builder, ai.eloquent.raft.KeyValueStateMachineProto.RemoveValueOrBuilder> getRemoveValueFieldBuilder() { if (removeValueBuilder_ == null) { if (!(bodyCase_ == 6)) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.getDefaultInstance(); } removeValueBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue, ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.Builder, ai.eloquent.raft.KeyValueStateMachineProto.RemoveValueOrBuilder>( (ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) body_, getParentForChildren(), isClean()); body_ = null; } bodyCase_ = 6; onChanged();; return removeValueBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients, ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.Builder, ai.eloquent.raft.KeyValueStateMachineProto.ClearTransientsOrBuilder> clearTransientsBuilder_; /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public boolean hasClearTransients() { return bodyCase_ == 7; } /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients getClearTransients() { if (clearTransientsBuilder_ == null) { if (bodyCase_ == 7) { return (ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.getDefaultInstance(); } else { if (bodyCase_ == 7) { return clearTransientsBuilder_.getMessage(); } return ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public Builder setClearTransients(ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients value) { if (clearTransientsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } body_ = value; onChanged(); } else { clearTransientsBuilder_.setMessage(value); } bodyCase_ = 7; return this; } /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public Builder setClearTransients( ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.Builder builderForValue) { if (clearTransientsBuilder_ == null) { body_ = builderForValue.build(); onChanged(); } else { clearTransientsBuilder_.setMessage(builderForValue.build()); } bodyCase_ = 7; return this; } /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public Builder mergeClearTransients(ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients value) { if (clearTransientsBuilder_ == null) { if (bodyCase_ == 7 && body_ != ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.getDefaultInstance()) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.newBuilder((ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) body_) .mergeFrom(value).buildPartial(); } else { body_ = value; } onChanged(); } else { if (bodyCase_ == 7) { clearTransientsBuilder_.mergeFrom(value); } clearTransientsBuilder_.setMessage(value); } bodyCase_ = 7; return this; } /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public Builder clearClearTransients() { if (clearTransientsBuilder_ == null) { if (bodyCase_ == 7) { bodyCase_ = 0; body_ = null; onChanged(); } } else { if (bodyCase_ == 7) { bodyCase_ = 0; body_ = null; } clearTransientsBuilder_.clear(); } return this; } /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.Builder getClearTransientsBuilder() { return getClearTransientsFieldBuilder().getBuilder(); } /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.ClearTransientsOrBuilder getClearTransientsOrBuilder() { if ((bodyCase_ == 7) && (clearTransientsBuilder_ != null)) { return clearTransientsBuilder_.getMessageOrBuilder(); } else { if (bodyCase_ == 7) { return (ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) body_; } return ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.getDefaultInstance(); } } /** * <code>.ai.eloquent.raft.ClearTransients clearTransients = 7;</code> */ private com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients, ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.Builder, ai.eloquent.raft.KeyValueStateMachineProto.ClearTransientsOrBuilder> getClearTransientsFieldBuilder() { if (clearTransientsBuilder_ == null) { if (!(bodyCase_ == 7)) { body_ = ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.getDefaultInstance(); } clearTransientsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients, ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.Builder, ai.eloquent.raft.KeyValueStateMachineProto.ClearTransientsOrBuilder>( (ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) body_, getParentForChildren(), isClean()); body_ = null; } bodyCase_ = 7; onChanged();; return clearTransientsBuilder_; } private java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.Transition> transitions_ = java.util.Collections.emptyList(); private void ensureTransitionsIsMutable() { if (!((bitField0_ & 0x00000080) == 0x00000080)) { transitions_ = new java.util.ArrayList<ai.eloquent.raft.KeyValueStateMachineProto.Transition>(transitions_); bitField0_ |= 0x00000080; } } private com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.Transition, ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder, ai.eloquent.raft.KeyValueStateMachineProto.TransitionOrBuilder> transitionsBuilder_; /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.Transition> getTransitionsList() { if (transitionsBuilder_ == null) { return java.util.Collections.unmodifiableList(transitions_); } else { return transitionsBuilder_.getMessageList(); } } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public int getTransitionsCount() { if (transitionsBuilder_ == null) { return transitions_.size(); } else { return transitionsBuilder_.getCount(); } } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.Transition getTransitions(int index) { if (transitionsBuilder_ == null) { return transitions_.get(index); } else { return transitionsBuilder_.getMessage(index); } } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public Builder setTransitions( int index, ai.eloquent.raft.KeyValueStateMachineProto.Transition value) { if (transitionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTransitionsIsMutable(); transitions_.set(index, value); onChanged(); } else { transitionsBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public Builder setTransitions( int index, ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder builderForValue) { if (transitionsBuilder_ == null) { ensureTransitionsIsMutable(); transitions_.set(index, builderForValue.build()); onChanged(); } else { transitionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public Builder addTransitions(ai.eloquent.raft.KeyValueStateMachineProto.Transition value) { if (transitionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTransitionsIsMutable(); transitions_.add(value); onChanged(); } else { transitionsBuilder_.addMessage(value); } return this; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public Builder addTransitions( int index, ai.eloquent.raft.KeyValueStateMachineProto.Transition value) { if (transitionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTransitionsIsMutable(); transitions_.add(index, value); onChanged(); } else { transitionsBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public Builder addTransitions( ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder builderForValue) { if (transitionsBuilder_ == null) { ensureTransitionsIsMutable(); transitions_.add(builderForValue.build()); onChanged(); } else { transitionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public Builder addTransitions( int index, ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder builderForValue) { if (transitionsBuilder_ == null) { ensureTransitionsIsMutable(); transitions_.add(index, builderForValue.build()); onChanged(); } else { transitionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public Builder addAllTransitions( java.lang.Iterable<? extends ai.eloquent.raft.KeyValueStateMachineProto.Transition> values) { if (transitionsBuilder_ == null) { ensureTransitionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, transitions_); onChanged(); } else { transitionsBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public Builder clearTransitions() { if (transitionsBuilder_ == null) { transitions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000080); onChanged(); } else { transitionsBuilder_.clear(); } return this; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public Builder removeTransitions(int index) { if (transitionsBuilder_ == null) { ensureTransitionsIsMutable(); transitions_.remove(index); onChanged(); } else { transitionsBuilder_.remove(index); } return this; } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder getTransitionsBuilder( int index) { return getTransitionsFieldBuilder().getBuilder(index); } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.TransitionOrBuilder getTransitionsOrBuilder( int index) { if (transitionsBuilder_ == null) { return transitions_.get(index); } else { return transitionsBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public java.util.List<? extends ai.eloquent.raft.KeyValueStateMachineProto.TransitionOrBuilder> getTransitionsOrBuilderList() { if (transitionsBuilder_ != null) { return transitionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(transitions_); } } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder addTransitionsBuilder() { return getTransitionsFieldBuilder().addBuilder( ai.eloquent.raft.KeyValueStateMachineProto.Transition.getDefaultInstance()); } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder addTransitionsBuilder( int index) { return getTransitionsFieldBuilder().addBuilder( index, ai.eloquent.raft.KeyValueStateMachineProto.Transition.getDefaultInstance()); } /** * <code>repeated .ai.eloquent.raft.Transition transitions = 8;</code> */ public java.util.List<ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder> getTransitionsBuilderList() { return getTransitionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.Transition, ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder, ai.eloquent.raft.KeyValueStateMachineProto.TransitionOrBuilder> getTransitionsFieldBuilder() { if (transitionsBuilder_ == null) { transitionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< ai.eloquent.raft.KeyValueStateMachineProto.Transition, ai.eloquent.raft.KeyValueStateMachineProto.Transition.Builder, ai.eloquent.raft.KeyValueStateMachineProto.TransitionOrBuilder>( transitions_, ((bitField0_ & 0x00000080) == 0x00000080), getParentForChildren(), isClean()); transitions_ = null; } return transitionsBuilder_; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.Transition) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.Transition) private static final ai.eloquent.raft.KeyValueStateMachineProto.Transition DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.Transition(); } public static ai.eloquent.raft.KeyValueStateMachineProto.Transition getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Transition> PARSER = new com.google.protobuf.AbstractParser<Transition>() { public Transition parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Transition(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Transition> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Transition> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.Transition getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface RequestLockOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.RequestLock) com.google.protobuf.MessageOrBuilder { /** * <code>string lock = 1;</code> */ java.lang.String getLock(); /** * <code>string lock = 1;</code> */ com.google.protobuf.ByteString getLockBytes(); /** * <code>string requester = 2;</code> */ java.lang.String getRequester(); /** * <code>string requester = 2;</code> */ com.google.protobuf.ByteString getRequesterBytes(); /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ java.lang.String getUniqueHash(); /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ com.google.protobuf.ByteString getUniqueHashBytes(); } /** * Protobuf type {@code ai.eloquent.raft.RequestLock} */ public static final class RequestLock extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.RequestLock) RequestLockOrBuilder { private static final long serialVersionUID = 0L; // Use RequestLock.newBuilder() to construct. private RequestLock(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RequestLock() { lock_ = ""; requester_ = ""; uniqueHash_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private RequestLock( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); lock_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); requester_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); uniqueHash_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_RequestLock_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_RequestLock_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.class, ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.Builder.class); } public static final int LOCK_FIELD_NUMBER = 1; private volatile java.lang.Object lock_; /** * <code>string lock = 1;</code> */ public java.lang.String getLock() { java.lang.Object ref = lock_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lock_ = s; return s; } } /** * <code>string lock = 1;</code> */ public com.google.protobuf.ByteString getLockBytes() { java.lang.Object ref = lock_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lock_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUESTER_FIELD_NUMBER = 2; private volatile java.lang.Object requester_; /** * <code>string requester = 2;</code> */ public java.lang.String getRequester() { java.lang.Object ref = requester_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requester_ = s; return s; } } /** * <code>string requester = 2;</code> */ public com.google.protobuf.ByteString getRequesterBytes() { java.lang.Object ref = requester_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requester_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int UNIQUEHASH_FIELD_NUMBER = 3; private volatile java.lang.Object uniqueHash_; /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public java.lang.String getUniqueHash() { java.lang.Object ref = uniqueHash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uniqueHash_ = s; return s; } } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public com.google.protobuf.ByteString getUniqueHashBytes() { java.lang.Object ref = uniqueHash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uniqueHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getLockBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, lock_); } if (!getRequesterBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, requester_); } if (!getUniqueHashBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, uniqueHash_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getLockBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, lock_); } if (!getRequesterBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, requester_); } if (!getUniqueHashBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, uniqueHash_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.RequestLock)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.RequestLock other = (ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) obj; boolean result = true; result = result && getLock() .equals(other.getLock()); result = result && getRequester() .equals(other.getRequester()); result = result && getUniqueHash() .equals(other.getUniqueHash()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LOCK_FIELD_NUMBER; hash = (53 * hash) + getLock().hashCode(); hash = (37 * hash) + REQUESTER_FIELD_NUMBER; hash = (53 * hash) + getRequester().hashCode(); hash = (37 * hash) + UNIQUEHASH_FIELD_NUMBER; hash = (53 * hash) + getUniqueHash().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.RequestLock prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.RequestLock} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.RequestLock) ai.eloquent.raft.KeyValueStateMachineProto.RequestLockOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_RequestLock_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_RequestLock_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.class, ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); lock_ = ""; requester_ = ""; uniqueHash_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_RequestLock_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.RequestLock getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.RequestLock build() { ai.eloquent.raft.KeyValueStateMachineProto.RequestLock result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.RequestLock buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.RequestLock result = new ai.eloquent.raft.KeyValueStateMachineProto.RequestLock(this); result.lock_ = lock_; result.requester_ = requester_; result.uniqueHash_ = uniqueHash_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.RequestLock)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.RequestLock other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.RequestLock.getDefaultInstance()) return this; if (!other.getLock().isEmpty()) { lock_ = other.lock_; onChanged(); } if (!other.getRequester().isEmpty()) { requester_ = other.requester_; onChanged(); } if (!other.getUniqueHash().isEmpty()) { uniqueHash_ = other.uniqueHash_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.RequestLock parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.RequestLock) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object lock_ = ""; /** * <code>string lock = 1;</code> */ public java.lang.String getLock() { java.lang.Object ref = lock_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lock_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string lock = 1;</code> */ public com.google.protobuf.ByteString getLockBytes() { java.lang.Object ref = lock_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lock_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string lock = 1;</code> */ public Builder setLock( java.lang.String value) { if (value == null) { throw new NullPointerException(); } lock_ = value; onChanged(); return this; } /** * <code>string lock = 1;</code> */ public Builder clearLock() { lock_ = getDefaultInstance().getLock(); onChanged(); return this; } /** * <code>string lock = 1;</code> */ public Builder setLockBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); lock_ = value; onChanged(); return this; } private java.lang.Object requester_ = ""; /** * <code>string requester = 2;</code> */ public java.lang.String getRequester() { java.lang.Object ref = requester_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requester_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string requester = 2;</code> */ public com.google.protobuf.ByteString getRequesterBytes() { java.lang.Object ref = requester_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requester_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string requester = 2;</code> */ public Builder setRequester( java.lang.String value) { if (value == null) { throw new NullPointerException(); } requester_ = value; onChanged(); return this; } /** * <code>string requester = 2;</code> */ public Builder clearRequester() { requester_ = getDefaultInstance().getRequester(); onChanged(); return this; } /** * <code>string requester = 2;</code> */ public Builder setRequesterBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requester_ = value; onChanged(); return this; } private java.lang.Object uniqueHash_ = ""; /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public java.lang.String getUniqueHash() { java.lang.Object ref = uniqueHash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uniqueHash_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public com.google.protobuf.ByteString getUniqueHashBytes() { java.lang.Object ref = uniqueHash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uniqueHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public Builder setUniqueHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } uniqueHash_ = value; onChanged(); return this; } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public Builder clearUniqueHash() { uniqueHash_ = getDefaultInstance().getUniqueHash(); onChanged(); return this; } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public Builder setUniqueHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); uniqueHash_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.RequestLock) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.RequestLock) private static final ai.eloquent.raft.KeyValueStateMachineProto.RequestLock DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.RequestLock(); } public static ai.eloquent.raft.KeyValueStateMachineProto.RequestLock getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RequestLock> PARSER = new com.google.protobuf.AbstractParser<RequestLock>() { public RequestLock parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new RequestLock(input, extensionRegistry); } }; public static com.google.protobuf.Parser<RequestLock> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RequestLock> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.RequestLock getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface TryLockOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.TryLock) com.google.protobuf.MessageOrBuilder { /** * <code>string lock = 1;</code> */ java.lang.String getLock(); /** * <code>string lock = 1;</code> */ com.google.protobuf.ByteString getLockBytes(); /** * <code>string requester = 2;</code> */ java.lang.String getRequester(); /** * <code>string requester = 2;</code> */ com.google.protobuf.ByteString getRequesterBytes(); /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ java.lang.String getUniqueHash(); /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ com.google.protobuf.ByteString getUniqueHashBytes(); } /** * Protobuf type {@code ai.eloquent.raft.TryLock} */ public static final class TryLock extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.TryLock) TryLockOrBuilder { private static final long serialVersionUID = 0L; // Use TryLock.newBuilder() to construct. private TryLock(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private TryLock() { lock_ = ""; requester_ = ""; uniqueHash_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TryLock( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); lock_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); requester_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); uniqueHash_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_TryLock_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_TryLock_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.TryLock.class, ai.eloquent.raft.KeyValueStateMachineProto.TryLock.Builder.class); } public static final int LOCK_FIELD_NUMBER = 1; private volatile java.lang.Object lock_; /** * <code>string lock = 1;</code> */ public java.lang.String getLock() { java.lang.Object ref = lock_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lock_ = s; return s; } } /** * <code>string lock = 1;</code> */ public com.google.protobuf.ByteString getLockBytes() { java.lang.Object ref = lock_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lock_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUESTER_FIELD_NUMBER = 2; private volatile java.lang.Object requester_; /** * <code>string requester = 2;</code> */ public java.lang.String getRequester() { java.lang.Object ref = requester_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requester_ = s; return s; } } /** * <code>string requester = 2;</code> */ public com.google.protobuf.ByteString getRequesterBytes() { java.lang.Object ref = requester_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requester_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int UNIQUEHASH_FIELD_NUMBER = 3; private volatile java.lang.Object uniqueHash_; /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public java.lang.String getUniqueHash() { java.lang.Object ref = uniqueHash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uniqueHash_ = s; return s; } } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public com.google.protobuf.ByteString getUniqueHashBytes() { java.lang.Object ref = uniqueHash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uniqueHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getLockBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, lock_); } if (!getRequesterBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, requester_); } if (!getUniqueHashBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, uniqueHash_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getLockBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, lock_); } if (!getRequesterBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, requester_); } if (!getUniqueHashBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, uniqueHash_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.TryLock)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.TryLock other = (ai.eloquent.raft.KeyValueStateMachineProto.TryLock) obj; boolean result = true; result = result && getLock() .equals(other.getLock()); result = result && getRequester() .equals(other.getRequester()); result = result && getUniqueHash() .equals(other.getUniqueHash()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LOCK_FIELD_NUMBER; hash = (53 * hash) + getLock().hashCode(); hash = (37 * hash) + REQUESTER_FIELD_NUMBER; hash = (53 * hash) + getRequester().hashCode(); hash = (37 * hash) + UNIQUEHASH_FIELD_NUMBER; hash = (53 * hash) + getUniqueHash().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.TryLock prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.TryLock} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.TryLock) ai.eloquent.raft.KeyValueStateMachineProto.TryLockOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_TryLock_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_TryLock_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.TryLock.class, ai.eloquent.raft.KeyValueStateMachineProto.TryLock.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.TryLock.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); lock_ = ""; requester_ = ""; uniqueHash_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_TryLock_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.TryLock getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.TryLock.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.TryLock build() { ai.eloquent.raft.KeyValueStateMachineProto.TryLock result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.TryLock buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.TryLock result = new ai.eloquent.raft.KeyValueStateMachineProto.TryLock(this); result.lock_ = lock_; result.requester_ = requester_; result.uniqueHash_ = uniqueHash_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.TryLock) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.TryLock)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.TryLock other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.TryLock.getDefaultInstance()) return this; if (!other.getLock().isEmpty()) { lock_ = other.lock_; onChanged(); } if (!other.getRequester().isEmpty()) { requester_ = other.requester_; onChanged(); } if (!other.getUniqueHash().isEmpty()) { uniqueHash_ = other.uniqueHash_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.TryLock parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.TryLock) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object lock_ = ""; /** * <code>string lock = 1;</code> */ public java.lang.String getLock() { java.lang.Object ref = lock_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lock_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string lock = 1;</code> */ public com.google.protobuf.ByteString getLockBytes() { java.lang.Object ref = lock_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lock_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string lock = 1;</code> */ public Builder setLock( java.lang.String value) { if (value == null) { throw new NullPointerException(); } lock_ = value; onChanged(); return this; } /** * <code>string lock = 1;</code> */ public Builder clearLock() { lock_ = getDefaultInstance().getLock(); onChanged(); return this; } /** * <code>string lock = 1;</code> */ public Builder setLockBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); lock_ = value; onChanged(); return this; } private java.lang.Object requester_ = ""; /** * <code>string requester = 2;</code> */ public java.lang.String getRequester() { java.lang.Object ref = requester_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requester_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string requester = 2;</code> */ public com.google.protobuf.ByteString getRequesterBytes() { java.lang.Object ref = requester_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requester_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string requester = 2;</code> */ public Builder setRequester( java.lang.String value) { if (value == null) { throw new NullPointerException(); } requester_ = value; onChanged(); return this; } /** * <code>string requester = 2;</code> */ public Builder clearRequester() { requester_ = getDefaultInstance().getRequester(); onChanged(); return this; } /** * <code>string requester = 2;</code> */ public Builder setRequesterBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requester_ = value; onChanged(); return this; } private java.lang.Object uniqueHash_ = ""; /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public java.lang.String getUniqueHash() { java.lang.Object ref = uniqueHash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uniqueHash_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public com.google.protobuf.ByteString getUniqueHashBytes() { java.lang.Object ref = uniqueHash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uniqueHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public Builder setUniqueHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } uniqueHash_ = value; onChanged(); return this; } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public Builder clearUniqueHash() { uniqueHash_ = getDefaultInstance().getUniqueHash(); onChanged(); return this; } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public Builder setUniqueHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); uniqueHash_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.TryLock) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.TryLock) private static final ai.eloquent.raft.KeyValueStateMachineProto.TryLock DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.TryLock(); } public static ai.eloquent.raft.KeyValueStateMachineProto.TryLock getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<TryLock> PARSER = new com.google.protobuf.AbstractParser<TryLock>() { public TryLock parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TryLock(input, extensionRegistry); } }; public static com.google.protobuf.Parser<TryLock> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<TryLock> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.TryLock getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ReleaseLockOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.ReleaseLock) com.google.protobuf.MessageOrBuilder { /** * <code>string lock = 1;</code> */ java.lang.String getLock(); /** * <code>string lock = 1;</code> */ com.google.protobuf.ByteString getLockBytes(); /** * <code>string requester = 2;</code> */ java.lang.String getRequester(); /** * <code>string requester = 2;</code> */ com.google.protobuf.ByteString getRequesterBytes(); /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ java.lang.String getUniqueHash(); /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ com.google.protobuf.ByteString getUniqueHashBytes(); } /** * Protobuf type {@code ai.eloquent.raft.ReleaseLock} */ public static final class ReleaseLock extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.ReleaseLock) ReleaseLockOrBuilder { private static final long serialVersionUID = 0L; // Use ReleaseLock.newBuilder() to construct. private ReleaseLock(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ReleaseLock() { lock_ = ""; requester_ = ""; uniqueHash_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ReleaseLock( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); lock_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); requester_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); uniqueHash_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ReleaseLock_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ReleaseLock_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.class, ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.Builder.class); } public static final int LOCK_FIELD_NUMBER = 1; private volatile java.lang.Object lock_; /** * <code>string lock = 1;</code> */ public java.lang.String getLock() { java.lang.Object ref = lock_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lock_ = s; return s; } } /** * <code>string lock = 1;</code> */ public com.google.protobuf.ByteString getLockBytes() { java.lang.Object ref = lock_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lock_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUESTER_FIELD_NUMBER = 2; private volatile java.lang.Object requester_; /** * <code>string requester = 2;</code> */ public java.lang.String getRequester() { java.lang.Object ref = requester_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requester_ = s; return s; } } /** * <code>string requester = 2;</code> */ public com.google.protobuf.ByteString getRequesterBytes() { java.lang.Object ref = requester_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requester_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int UNIQUEHASH_FIELD_NUMBER = 3; private volatile java.lang.Object uniqueHash_; /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public java.lang.String getUniqueHash() { java.lang.Object ref = uniqueHash_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uniqueHash_ = s; return s; } } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public com.google.protobuf.ByteString getUniqueHashBytes() { java.lang.Object ref = uniqueHash_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uniqueHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getLockBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, lock_); } if (!getRequesterBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, requester_); } if (!getUniqueHashBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, uniqueHash_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getLockBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, lock_); } if (!getRequesterBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, requester_); } if (!getUniqueHashBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, uniqueHash_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock other = (ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) obj; boolean result = true; result = result && getLock() .equals(other.getLock()); result = result && getRequester() .equals(other.getRequester()); result = result && getUniqueHash() .equals(other.getUniqueHash()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LOCK_FIELD_NUMBER; hash = (53 * hash) + getLock().hashCode(); hash = (37 * hash) + REQUESTER_FIELD_NUMBER; hash = (53 * hash) + getRequester().hashCode(); hash = (37 * hash) + UNIQUEHASH_FIELD_NUMBER; hash = (53 * hash) + getUniqueHash().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.ReleaseLock} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.ReleaseLock) ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLockOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ReleaseLock_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ReleaseLock_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.class, ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); lock_ = ""; requester_ = ""; uniqueHash_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ReleaseLock_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock build() { ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock result = new ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock(this); result.lock_ = lock_; result.requester_ = requester_; result.uniqueHash_ = uniqueHash_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock.getDefaultInstance()) return this; if (!other.getLock().isEmpty()) { lock_ = other.lock_; onChanged(); } if (!other.getRequester().isEmpty()) { requester_ = other.requester_; onChanged(); } if (!other.getUniqueHash().isEmpty()) { uniqueHash_ = other.uniqueHash_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object lock_ = ""; /** * <code>string lock = 1;</code> */ public java.lang.String getLock() { java.lang.Object ref = lock_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lock_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string lock = 1;</code> */ public com.google.protobuf.ByteString getLockBytes() { java.lang.Object ref = lock_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lock_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string lock = 1;</code> */ public Builder setLock( java.lang.String value) { if (value == null) { throw new NullPointerException(); } lock_ = value; onChanged(); return this; } /** * <code>string lock = 1;</code> */ public Builder clearLock() { lock_ = getDefaultInstance().getLock(); onChanged(); return this; } /** * <code>string lock = 1;</code> */ public Builder setLockBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); lock_ = value; onChanged(); return this; } private java.lang.Object requester_ = ""; /** * <code>string requester = 2;</code> */ public java.lang.String getRequester() { java.lang.Object ref = requester_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requester_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string requester = 2;</code> */ public com.google.protobuf.ByteString getRequesterBytes() { java.lang.Object ref = requester_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requester_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string requester = 2;</code> */ public Builder setRequester( java.lang.String value) { if (value == null) { throw new NullPointerException(); } requester_ = value; onChanged(); return this; } /** * <code>string requester = 2;</code> */ public Builder clearRequester() { requester_ = getDefaultInstance().getRequester(); onChanged(); return this; } /** * <code>string requester = 2;</code> */ public Builder setRequesterBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requester_ = value; onChanged(); return this; } private java.lang.Object uniqueHash_ = ""; /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public java.lang.String getUniqueHash() { java.lang.Object ref = uniqueHash_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uniqueHash_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public com.google.protobuf.ByteString getUniqueHashBytes() { java.lang.Object ref = uniqueHash_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); uniqueHash_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public Builder setUniqueHash( java.lang.String value) { if (value == null) { throw new NullPointerException(); } uniqueHash_ = value; onChanged(); return this; } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public Builder clearUniqueHash() { uniqueHash_ = getDefaultInstance().getUniqueHash(); onChanged(); return this; } /** * <pre> * This is used to prevent multiple people from taking the same lock on the same box * </pre> * * <code>string uniqueHash = 3;</code> */ public Builder setUniqueHashBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); uniqueHash_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.ReleaseLock) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.ReleaseLock) private static final ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock(); } public static ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ReleaseLock> PARSER = new com.google.protobuf.AbstractParser<ReleaseLock>() { public ReleaseLock parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ReleaseLock(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ReleaseLock> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ReleaseLock> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.ReleaseLock getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SetValueOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.SetValue) com.google.protobuf.MessageOrBuilder { /** * <code>string key = 1;</code> */ java.lang.String getKey(); /** * <code>string key = 1;</code> */ com.google.protobuf.ByteString getKeyBytes(); /** * <code>bytes value = 2;</code> */ com.google.protobuf.ByteString getValue(); /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 3;</code> */ java.lang.String getOwner(); /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 3;</code> */ com.google.protobuf.ByteString getOwnerBytes(); } /** * Protobuf type {@code ai.eloquent.raft.SetValue} */ public static final class SetValue extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.SetValue) SetValueOrBuilder { private static final long serialVersionUID = 0L; // Use SetValue.newBuilder() to construct. private SetValue(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SetValue() { key_ = ""; value_ = com.google.protobuf.ByteString.EMPTY; owner_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SetValue( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); key_ = s; break; } case 18: { value_ = input.readBytes(); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); owner_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_SetValue_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_SetValue_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.SetValue.class, ai.eloquent.raft.KeyValueStateMachineProto.SetValue.Builder.class); } public static final int KEY_FIELD_NUMBER = 1; private volatile java.lang.Object key_; /** * <code>string key = 1;</code> */ public java.lang.String getKey() { java.lang.Object ref = key_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); key_ = s; return s; } } /** * <code>string key = 1;</code> */ public com.google.protobuf.ByteString getKeyBytes() { java.lang.Object ref = key_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); key_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALUE_FIELD_NUMBER = 2; private com.google.protobuf.ByteString value_; /** * <code>bytes value = 2;</code> */ public com.google.protobuf.ByteString getValue() { return value_; } public static final int OWNER_FIELD_NUMBER = 3; private volatile java.lang.Object owner_; /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 3;</code> */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } } /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 3;</code> */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getKeyBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, key_); } if (!value_.isEmpty()) { output.writeBytes(2, value_); } if (!getOwnerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, owner_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getKeyBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, key_); } if (!value_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, value_); } if (!getOwnerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, owner_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.SetValue)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.SetValue other = (ai.eloquent.raft.KeyValueStateMachineProto.SetValue) obj; boolean result = true; result = result && getKey() .equals(other.getKey()); result = result && getValue() .equals(other.getValue()); result = result && getOwner() .equals(other.getOwner()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + KEY_FIELD_NUMBER; hash = (53 * hash) + getKey().hashCode(); hash = (37 * hash) + VALUE_FIELD_NUMBER; hash = (53 * hash) + getValue().hashCode(); hash = (37 * hash) + OWNER_FIELD_NUMBER; hash = (53 * hash) + getOwner().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.SetValue prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.SetValue} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.SetValue) ai.eloquent.raft.KeyValueStateMachineProto.SetValueOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_SetValue_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_SetValue_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.SetValue.class, ai.eloquent.raft.KeyValueStateMachineProto.SetValue.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.SetValue.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); key_ = ""; value_ = com.google.protobuf.ByteString.EMPTY; owner_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_SetValue_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.SetValue getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.SetValue.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.SetValue build() { ai.eloquent.raft.KeyValueStateMachineProto.SetValue result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.SetValue buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.SetValue result = new ai.eloquent.raft.KeyValueStateMachineProto.SetValue(this); result.key_ = key_; result.value_ = value_; result.owner_ = owner_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.SetValue) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.SetValue)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.SetValue other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.SetValue.getDefaultInstance()) return this; if (!other.getKey().isEmpty()) { key_ = other.key_; onChanged(); } if (other.getValue() != com.google.protobuf.ByteString.EMPTY) { setValue(other.getValue()); } if (!other.getOwner().isEmpty()) { owner_ = other.owner_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.SetValue parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.SetValue) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object key_ = ""; /** * <code>string key = 1;</code> */ public java.lang.String getKey() { java.lang.Object ref = key_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); key_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string key = 1;</code> */ public com.google.protobuf.ByteString getKeyBytes() { java.lang.Object ref = key_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); key_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string key = 1;</code> */ public Builder setKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } key_ = value; onChanged(); return this; } /** * <code>string key = 1;</code> */ public Builder clearKey() { key_ = getDefaultInstance().getKey(); onChanged(); return this; } /** * <code>string key = 1;</code> */ public Builder setKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); key_ = value; onChanged(); return this; } private com.google.protobuf.ByteString value_ = com.google.protobuf.ByteString.EMPTY; /** * <code>bytes value = 2;</code> */ public com.google.protobuf.ByteString getValue() { return value_; } /** * <code>bytes value = 2;</code> */ public Builder setValue(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } value_ = value; onChanged(); return this; } /** * <code>bytes value = 2;</code> */ public Builder clearValue() { value_ = getDefaultInstance().getValue(); onChanged(); return this; } private java.lang.Object owner_ = ""; /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 3;</code> */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 3;</code> */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 3;</code> */ public Builder setOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } owner_ = value; onChanged(); return this; } /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 3;</code> */ public Builder clearOwner() { owner_ = getDefaultInstance().getOwner(); onChanged(); return this; } /** * <pre> * if this is not empty, the value will be cleaned up automatically when the owner disconnects * </pre> * * <code>string owner = 3;</code> */ public Builder setOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); owner_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.SetValue) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.SetValue) private static final ai.eloquent.raft.KeyValueStateMachineProto.SetValue DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.SetValue(); } public static ai.eloquent.raft.KeyValueStateMachineProto.SetValue getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SetValue> PARSER = new com.google.protobuf.AbstractParser<SetValue>() { public SetValue parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SetValue(input, extensionRegistry); } }; public static com.google.protobuf.Parser<SetValue> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SetValue> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.SetValue getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface RemoveValueOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.RemoveValue) com.google.protobuf.MessageOrBuilder { /** * <code>string key = 1;</code> */ java.lang.String getKey(); /** * <code>string key = 1;</code> */ com.google.protobuf.ByteString getKeyBytes(); } /** * Protobuf type {@code ai.eloquent.raft.RemoveValue} */ public static final class RemoveValue extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.RemoveValue) RemoveValueOrBuilder { private static final long serialVersionUID = 0L; // Use RemoveValue.newBuilder() to construct. private RemoveValue(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RemoveValue() { key_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private RemoveValue( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); key_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_RemoveValue_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_RemoveValue_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.class, ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.Builder.class); } public static final int KEY_FIELD_NUMBER = 1; private volatile java.lang.Object key_; /** * <code>string key = 1;</code> */ public java.lang.String getKey() { java.lang.Object ref = key_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); key_ = s; return s; } } /** * <code>string key = 1;</code> */ public com.google.protobuf.ByteString getKeyBytes() { java.lang.Object ref = key_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); key_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getKeyBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, key_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getKeyBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, key_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue other = (ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) obj; boolean result = true; result = result && getKey() .equals(other.getKey()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + KEY_FIELD_NUMBER; hash = (53 * hash) + getKey().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.RemoveValue} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.RemoveValue) ai.eloquent.raft.KeyValueStateMachineProto.RemoveValueOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_RemoveValue_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_RemoveValue_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.class, ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); key_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_RemoveValue_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue build() { ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue result = new ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue(this); result.key_ = key_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue.getDefaultInstance()) return this; if (!other.getKey().isEmpty()) { key_ = other.key_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object key_ = ""; /** * <code>string key = 1;</code> */ public java.lang.String getKey() { java.lang.Object ref = key_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); key_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string key = 1;</code> */ public com.google.protobuf.ByteString getKeyBytes() { java.lang.Object ref = key_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); key_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string key = 1;</code> */ public Builder setKey( java.lang.String value) { if (value == null) { throw new NullPointerException(); } key_ = value; onChanged(); return this; } /** * <code>string key = 1;</code> */ public Builder clearKey() { key_ = getDefaultInstance().getKey(); onChanged(); return this; } /** * <code>string key = 1;</code> */ public Builder setKeyBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); key_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.RemoveValue) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.RemoveValue) private static final ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue(); } public static ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RemoveValue> PARSER = new com.google.protobuf.AbstractParser<RemoveValue>() { public RemoveValue parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new RemoveValue(input, extensionRegistry); } }; public static com.google.protobuf.Parser<RemoveValue> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RemoveValue> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.RemoveValue getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface ClearTransientsOrBuilder extends // @@protoc_insertion_point(interface_extends:ai.eloquent.raft.ClearTransients) com.google.protobuf.MessageOrBuilder { /** * <code>string owner = 1;</code> */ java.lang.String getOwner(); /** * <code>string owner = 1;</code> */ com.google.protobuf.ByteString getOwnerBytes(); } /** * Protobuf type {@code ai.eloquent.raft.ClearTransients} */ public static final class ClearTransients extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ai.eloquent.raft.ClearTransients) ClearTransientsOrBuilder { private static final long serialVersionUID = 0L; // Use ClearTransients.newBuilder() to construct. private ClearTransients(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ClearTransients() { owner_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ClearTransients( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); owner_ = s; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ClearTransients_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ClearTransients_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.class, ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.Builder.class); } public static final int OWNER_FIELD_NUMBER = 1; private volatile java.lang.Object owner_; /** * <code>string owner = 1;</code> */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } } /** * <code>string owner = 1;</code> */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getOwnerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, owner_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getOwnerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, owner_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients)) { return super.equals(obj); } ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients other = (ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) obj; boolean result = true; result = result && getOwner() .equals(other.getOwner()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + OWNER_FIELD_NUMBER; hash = (53 * hash) + getOwner().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ai.eloquent.raft.ClearTransients} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ai.eloquent.raft.ClearTransients) ai.eloquent.raft.KeyValueStateMachineProto.ClearTransientsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ClearTransients_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ClearTransients_fieldAccessorTable .ensureFieldAccessorsInitialized( ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.class, ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.Builder.class); } // Construct using ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); owner_ = ""; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ai.eloquent.raft.KeyValueStateMachineProto.internal_static_ai_eloquent_raft_ClearTransients_descriptor; } public ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients getDefaultInstanceForType() { return ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.getDefaultInstance(); } public ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients build() { ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients buildPartial() { ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients result = new ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients(this); result.owner_ = owner_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) { return mergeFrom((ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients other) { if (other == ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients.getDefaultInstance()) return this; if (!other.getOwner().isEmpty()) { owner_ = other.owner_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object owner_ = ""; /** * <code>string owner = 1;</code> */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string owner = 1;</code> */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string owner = 1;</code> */ public Builder setOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } owner_ = value; onChanged(); return this; } /** * <code>string owner = 1;</code> */ public Builder clearOwner() { owner_ = getDefaultInstance().getOwner(); onChanged(); return this; } /** * <code>string owner = 1;</code> */ public Builder setOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); owner_ = value; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:ai.eloquent.raft.ClearTransients) } // @@protoc_insertion_point(class_scope:ai.eloquent.raft.ClearTransients) private static final ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients(); } public static ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ClearTransients> PARSER = new com.google.protobuf.AbstractParser<ClearTransients>() { public ClearTransients parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ClearTransients(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ClearTransients> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ClearTransients> getParserForType() { return PARSER; } public ai.eloquent.raft.KeyValueStateMachineProto.ClearTransients getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_KVStateMachine_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_KVStateMachine_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_KVStateMachine_ValuesEntry_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_KVStateMachine_ValuesEntry_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_KVStateMachine_LocksEntry_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_KVStateMachine_LocksEntry_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_ValueWithOptionalOwner_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_ValueWithOptionalOwner_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_QueueLock_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_QueueLock_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_LockRequest_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_LockRequest_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_Transition_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_Transition_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_RequestLock_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_RequestLock_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_TryLock_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_TryLock_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_ReleaseLock_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_ReleaseLock_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_SetValue_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_SetValue_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_RemoveValue_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_RemoveValue_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_ai_eloquent_raft_ClearTransients_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ai_eloquent_raft_ClearTransients_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\032KeyValueStateMachine.proto\022\020ai.eloquen" + "t.raft\"\307\003\n\016KVStateMachine\022<\n\006values\030\001 \003(" + "\0132,.ai.eloquent.raft.KVStateMachine.Valu" + "esEntry\022:\n\005locks\030\002 \003(\0132+.ai.eloquent.raf" + "t.KVStateMachine.LocksEntry\022\022\n\nvaluesKey" + "s\030\003 \003(\t\022>\n\014valuesValues\030\004 \003(\0132(.ai.eloqu" + "ent.raft.ValueWithOptionalOwner\022\021\n\tlocks" + "Keys\030\005 \003(\t\0220\n\013locksValues\030\006 \003(\0132\033.ai.elo" + "quent.raft.QueueLock\032W\n\013ValuesEntry\022\013\n\003k" + "ey\030\001 \001(\t\0227\n\005value\030\002 \001(\0132(.ai.eloquent.ra" + "ft.ValueWithOptionalOwner:\0028\001\032I\n\nLocksEn" + "try\022\013\n\003key\030\001 \001(\t\022*\n\005value\030\002 \001(\0132\033.ai.elo" + "quent.raft.QueueLock:\0028\001\"a\n\026ValueWithOpt" + "ionalOwner\022\r\n\005value\030\001 \001(\014\022\r\n\005owner\030\002 \001(\t" + "\022\025\n\rlast_accessed\030\003 \001(\004\022\022\n\ncreated_at\030\004 " + "\001(\004\"j\n\tQueueLock\022-\n\006holder\030\001 \001(\0132\035.ai.el" + "oquent.raft.LockRequest\022.\n\007waiting\030\002 \003(\013" + "2\035.ai.eloquent.raft.LockRequest\"1\n\013LockR" + "equest\022\016\n\006server\030\001 \001(\t\022\022\n\nuniqueHash\030\002 \001" + "(\t\"\265\003\n\nTransition\022.\n\004type\030\001 \001(\0162 .ai.elo" + "quent.raft.TransitionType\0224\n\013requestLock" + "\030\002 \001(\0132\035.ai.eloquent.raft.RequestLockH\000\022" + ",\n\007tryLock\030\003 \001(\0132\031.ai.eloquent.raft.TryL" + "ockH\000\0224\n\013releaseLock\030\004 \001(\0132\035.ai.eloquent" + ".raft.ReleaseLockH\000\022.\n\010setValue\030\005 \001(\0132\032." + "ai.eloquent.raft.SetValueH\000\0224\n\013removeVal" + "ue\030\006 \001(\0132\035.ai.eloquent.raft.RemoveValueH" + "\000\022<\n\017clearTransients\030\007 \001(\0132!.ai.eloquent" + ".raft.ClearTransientsH\000\0221\n\013transitions\030\010" + " \003(\0132\034.ai.eloquent.raft.TransitionB\006\n\004bo" + "dy\"B\n\013RequestLock\022\014\n\004lock\030\001 \001(\t\022\021\n\treque" + "ster\030\002 \001(\t\022\022\n\nuniqueHash\030\003 \001(\t\">\n\007TryLoc" + "k\022\014\n\004lock\030\001 \001(\t\022\021\n\trequester\030\002 \001(\t\022\022\n\nun" + "iqueHash\030\003 \001(\t\"B\n\013ReleaseLock\022\014\n\004lock\030\001 " + "\001(\t\022\021\n\trequester\030\002 \001(\t\022\022\n\nuniqueHash\030\003 \001" + "(\t\"5\n\010SetValue\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030\002 \001" + "(\014\022\r\n\005owner\030\003 \001(\t\"\032\n\013RemoveValue\022\013\n\003key\030" + "\001 \001(\t\" \n\017ClearTransients\022\r\n\005owner\030\001 \001(\t*" + "\234\001\n\016TransitionType\022\013\n\007INVALID\020\000\022\020\n\014REQUE" + "ST_LOCK\020\006\022\020\n\014RELEASE_LOCK\020\001\022\014\n\010TRY_LOCK\020" + "\002\022\r\n\tSET_VALUE\020\003\022\020\n\014REMOVE_VALUE\020\004\022\024\n\020CL" + "EAR_TRANSIENTS\020\005\022\024\n\020TRANSITION_GROUP\020\007B-" + "\n\020ai.eloquent.raftB\031KeyValueStateMachine" + "Protob\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_ai_eloquent_raft_KVStateMachine_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_ai_eloquent_raft_KVStateMachine_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_KVStateMachine_descriptor, new java.lang.String[] { "Values", "Locks", "ValuesKeys", "ValuesValues", "LocksKeys", "LocksValues", }); internal_static_ai_eloquent_raft_KVStateMachine_ValuesEntry_descriptor = internal_static_ai_eloquent_raft_KVStateMachine_descriptor.getNestedTypes().get(0); internal_static_ai_eloquent_raft_KVStateMachine_ValuesEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_KVStateMachine_ValuesEntry_descriptor, new java.lang.String[] { "Key", "Value", }); internal_static_ai_eloquent_raft_KVStateMachine_LocksEntry_descriptor = internal_static_ai_eloquent_raft_KVStateMachine_descriptor.getNestedTypes().get(1); internal_static_ai_eloquent_raft_KVStateMachine_LocksEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_KVStateMachine_LocksEntry_descriptor, new java.lang.String[] { "Key", "Value", }); internal_static_ai_eloquent_raft_ValueWithOptionalOwner_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_ai_eloquent_raft_ValueWithOptionalOwner_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_ValueWithOptionalOwner_descriptor, new java.lang.String[] { "Value", "Owner", "LastAccessed", "CreatedAt", }); internal_static_ai_eloquent_raft_QueueLock_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_ai_eloquent_raft_QueueLock_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_QueueLock_descriptor, new java.lang.String[] { "Holder", "Waiting", }); internal_static_ai_eloquent_raft_LockRequest_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_ai_eloquent_raft_LockRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_LockRequest_descriptor, new java.lang.String[] { "Server", "UniqueHash", }); internal_static_ai_eloquent_raft_Transition_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_ai_eloquent_raft_Transition_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_Transition_descriptor, new java.lang.String[] { "Type", "RequestLock", "TryLock", "ReleaseLock", "SetValue", "RemoveValue", "ClearTransients", "Transitions", "Body", }); internal_static_ai_eloquent_raft_RequestLock_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_ai_eloquent_raft_RequestLock_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_RequestLock_descriptor, new java.lang.String[] { "Lock", "Requester", "UniqueHash", }); internal_static_ai_eloquent_raft_TryLock_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_ai_eloquent_raft_TryLock_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_TryLock_descriptor, new java.lang.String[] { "Lock", "Requester", "UniqueHash", }); internal_static_ai_eloquent_raft_ReleaseLock_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_ai_eloquent_raft_ReleaseLock_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_ReleaseLock_descriptor, new java.lang.String[] { "Lock", "Requester", "UniqueHash", }); internal_static_ai_eloquent_raft_SetValue_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_ai_eloquent_raft_SetValue_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_SetValue_descriptor, new java.lang.String[] { "Key", "Value", "Owner", }); internal_static_ai_eloquent_raft_RemoveValue_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_ai_eloquent_raft_RemoveValue_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_RemoveValue_descriptor, new java.lang.String[] { "Key", }); internal_static_ai_eloquent_raft_ClearTransients_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_ai_eloquent_raft_ClearTransients_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ai_eloquent_raft_ClearTransients_descriptor, new java.lang.String[] { "Owner", }); } // @@protoc_insertion_point(outer_class_scope) }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/LocalTransport.java
package ai.eloquent.raft; import ai.eloquent.util.*; import com.google.protobuf.InvalidProtocolBufferException; import ai.eloquent.util.IdentityHashSet; import ai.eloquent.util.RuntimeInterruptedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintWriter; import java.io.StringWriter; import java.time.Duration; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.stream.Collectors; /** * A mocked transport, that delivers messages to others listening on the same transport * instance. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class LocalTransport implements RaftTransport { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(LocalTransport.class); private volatile static StackTraceElement[] singleton = null; /** An event that can be queued on the transport. */ private interface TransportEvent {} /** * A simple object to represent a message over the wire. */ private class TransportMessage implements TransportEvent { /** A unique ID for the message. */ private final long id; /** The id of the inbound message, for resolving RPCs. */ private final long correlationId; /** The node name that sent this message. */ private final String sender; /** The node name that received this message. */ private final String target; /** The contents of the message we're sending, already serialized. */ private final byte[] contents; /** For debugging: the time at which the message was sent */ private final long sentAt; /** A straightforward constructor, with no correlation id. */ private TransportMessage(long id, String sender, String target, byte[] contents) { this(id, -1, sender, target, contents); } /** A straightforward constructor. */ private TransportMessage(long id, long correlationId, String sender, String target, byte[] contents) { this.id = id; this.correlationId = correlationId; this.sender = sender; this.target = target; this.contents = contents; this.sentAt = now(); } @Override public String toString() { try { EloquentRaftProto.RaftMessage raftMessage = EloquentRaftProto.RaftMessage.parseFrom(contents); String message = raftMessage.getContentsCase().toString()+" "; switch (raftMessage.getContentsCase()) { case APPENDENTRIES: message += raftMessage.getAppendEntries().toString(); break; case APPENDENTRIESREPLY: message += raftMessage.getAppendEntriesReply().toString(); break; case APPLYTRANSITION: message += raftMessage.getApplyTransition().toString(); break; case APPLYTRANSITIONREPLY: message += raftMessage.getApplyTransitionReply().toString(); break; } return "@"+this.sentAt+" :"+sender+"->"+target+": "+message.replaceAll("\n", ", "); } catch (InvalidProtocolBufferException e) { return "@"+this.sentAt+" :"+sender+"->"+target+": Unrecognized message"; } } } /** * A runnable task that can be queued on the transport. */ private class TransportTask implements TransportEvent { /** The task to run, taking the current time as an argument. */ private final Consumer<Long> task; /** For debugging: the time at which the event was queued */ private final long queuedAt; /** The call stack that led to this task */ private String stack; /** This lets us filter out TransportTasks that are queued up by the tests */ private boolean testTask; /** A straightforward constructor. */ private TransportTask(Consumer<Long> task) { this.task = task; this.queuedAt = now(); if (RaftLog.level() > 0) { // If we're not on TRACE, don't keep a stack from where this came from stack = ""; testTask = false; } else { try { throw new RuntimeException(); } catch (Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); stack = sw.toString(); testTask = stack.contains("AbstractRaftAlgorithmTest"); } } } @Override public String toString() { return "TransportTask from @"+this.queuedAt+": "+(testTask ? "AbstractRaftAlgorithmTest" : stack); } } /** * The specification for code awaiting a callback. */ private static class WaitingCallback { /** The message we sent that's waiting for a callback */ private final long messageId; /** The success function, if the callback returns. */ private final Consumer<EloquentRaftProto.RaftMessage> onSuccess; /** The timeout function, if the callback does not return. */ private final Runnable onTimeout; /** The time at which this message times out. */ private final long timeoutTime; /** The straightforward constructor. */ private WaitingCallback(long messageId, Consumer<EloquentRaftProto.RaftMessage> onSuccess, Runnable onTimeout, long timeoutTime) { this.messageId = messageId; this.onSuccess = onSuccess; this.onTimeout = onTimeout; this.timeoutTime = timeoutTime; } /** {@inheritDoc} */ @Override public String toString() { return "callback(" + messageId + ")@" + timeoutTime; } } /** * A network partition. Any given timestamp can have multiple of these. */ private static class Partition { /** The time at which this partition began. */ private final long startTime; /** The time at which this partition should be closed. */ private final long endTime; /** The members of the partition, partitioned off from the rest of the cluster but not from each other. */ private final Set<String> members; /** A straightforward constructor */ private Partition(long startTime, long endTime, String[] members) { this.startTime = startTime; this.endTime = endTime; this.members = new HashSet<>(Arrays.asList(members)); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Partition partition = (Partition) o; return startTime == partition.startTime && endTime == partition.endTime && Objects.equals(members, partition.members); } /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(startTime, endTime, members); } } /** The minimum amount of network delay. */ public final long delayMin; /** The maximum amount of network delay. */ public final long delayMax; /** The probability of dropping a packet on the "network." */ public final double dropProb; /** The probability of getting an IO exception when calling a transport function. */ public final double ioExceptionProb; /** If true, run in real-time (or close to). Otherwise, mock the transport time. */ public final boolean trueTime; /** The number of RPC messages this transport has sent. */ public long numRPCsSent = 0; /** A list of RPCs that are waiting for callbacks. */ private final Set<WaitingCallback> waitingCallbacks = new IdentityHashSet<>(); /** A counter for creating unique message ids. */ private final AtomicLong nextMessageId = new AtomicLong(0); /** The implementing algorithm. */ private List<RaftAlgorithm> nodes = new ArrayList<>(); private final ReadWriteLock nodesLock = new ReentrantReadWriteLock(); /** If true, this transport is still running. If false, we will exit from the thread loop. */ private boolean isAlive = true; /** A random number generator to use on the transport. */ private final Random rand; /** If true, this transport is still running. If false, we will exit from the thread loop. */ private final Thread timekeeper; /** This is a Future we can block on when we're waiting for the timekeeper thread to shut down. */ private final CompletableFuture<Void> timekeeperFinished; /** * The list of exceptions encountered by the transport. This should usually be empty at the end of a test. * You can verify this with {@link #assertNoErrors()}. */ public final List<Throwable> exceptions = new ArrayList<>(); /** The set of partition definitions we must respect. */ private final Set<Partition> partitions = new HashSet<>(); /** * This is the timer that we'll use to hook our events into the global mock clock. */ private final SafeTimerMock transportMockTimer = new SafeTimerMock(); /** Create a mock transport. */ public LocalTransport(long delayMin, long delayMax, double dropProb, double ioExceptionProb, boolean trueTime, long randomSeed) { // 1. Run error checks if (delayMin < 1 || delayMax < 0 || delayMax < delayMin || dropProb < 0.0 || dropProb > 1.0 || ioExceptionProb < 0 || ioExceptionProb > 1.0) { throw new IllegalArgumentException("Invalid params for mock Raft transport"); } if (singleton != null) { log.warn("Created two local transports at once. Old one created from:"); for (StackTraceElement s : singleton) { if (s.toString().startsWith("ai.eloquent")) { log.warn(" " + s.toString()); } } log.warn("New one is:"); for (StackTraceElement s : Thread.currentThread().getStackTrace()) { if (s.toString().startsWith("ai.eloquent")) { log.warn(" " + s.toString()); } } throw new RuntimeException("Two LocalTransports are running at the same time"); } singleton = Thread.currentThread().getStackTrace(); // 2. Set the variables this.delayMin = delayMin; this.delayMax = delayMax; this.dropProb = dropProb; this.ioExceptionProb = ioExceptionProb; this.trueTime = trueTime; this.rand = new Random(randomSeed); // 3. Start time this.timekeeperFinished = new CompletableFuture<>(); this.timekeeper = new Thread(() -> { while (true) { // Check if we've stopped the thread if (Thread.interrupted()) { throw new RuntimeInterruptedException(); } if (!isAlive) { transportMockTimer.cancel(); // cancel tasks before we stop break; } // can't synchronize on queue when we run this boolean shouldAdvanceTimer = false; synchronized (this) { // Actually move time forward by 1ms if (this.transportMockTimer.numTasksScheduled() > 0) { // don't move if nothing's happening shouldAdvanceTimer = true; } } // Advance time, but very very carefully if (shouldAdvanceTimer) { for (RaftAlgorithm algorithm : boundAlgorithms()) { // note[gabor] assume that all scheduled tasks will complete in 1ms or less; and wait for them to complete before advancing if (algorithm instanceof SingleThreadedRaftAlgorithm) { ((SingleThreadedRaftAlgorithm) algorithm).flush(() -> {}); } } Thread.yield(); // Never advance time while we're waiting on boundary pool threads to start while (SingleThreadedRaftAlgorithm.boundaryPoolThreadsWaiting.get() > 0) { for (RaftAlgorithm algorithm : boundAlgorithms()) { if (algorithm instanceof SingleThreadedRaftAlgorithm) { ((SingleThreadedRaftAlgorithm) algorithm).flush(() -> {}); } } Thread.yield(); } // OK, now we can advance time SafeTimerMock.advanceTime(1); } if (this.trueTime) { Uninterruptably.sleep(1); // run at 1ms per ms, give or take } else { Thread.yield(); } } timekeeperFinished.complete(null); }); timekeeper.setName("mock-raft-transport-time"); timekeeper.setDaemon(true); timekeeper.setPriority(Thread.MIN_PRIORITY); // run this guy at low priority timekeeper.setUncaughtExceptionHandler((t, e) -> { log.warn("Caught exception on timekeeper: ", e); isAlive = false; }); } /** A constructor that has presets for whether the transport is stable (i.e., lossless, etc.) or not */ public LocalTransport(boolean stable) { this(5, 100, stable ? 0.0 : 0.3, stable ? 0.0 : 0.3, false, 42L); } /** A constructor that has presets for whether the transport is stable (i.e., lossless, etc.) or not, and whether we should run in true time */ public LocalTransport(boolean stable, boolean trueTime) { this(5, 100, stable ? 0.0 : 0.3, stable ? 0.0 : 0.3, trueTime, 42L); } /** Creates a stable transport. */ @SuppressWarnings("unused") public LocalTransport() { this(true); } /** * A really stupid little function to ensure that no synchronized function is being run on any of the nodes. * This is useful for ensuring that time can proceed. */ private void silenceOn(Iterator<?> toSynchronizeOn, Runnable toRun) { if (toSynchronizeOn.hasNext()) { final Object o = toSynchronizeOn.next(); if (o != null) { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized(o) { silenceOn(toSynchronizeOn, toRun); } } } else { toRun.run(); } } /** * Run a block of code while synrhronizing on the current timestep. * This prevents the clock from slipping between lines of code * * @param r The runnable to run. */ public void synchronizedRun(Runnable r) { r.run(); } /** * Wait for the transport to fall silent. */ public void waitForSilence() { log.info("[{}] Waiting for transport to flush. queue_size={}", now(), transportMockTimer.numTasksScheduled()); try { transportMockTimer.waitForSilence(); log.info("[{}] Transport has flushed.", now()); } catch (Throwable t) { // Kill the main thread, just so we don't leak threads if this test failed in a suite of tests this.isAlive = false; // Wait for the main thread to die try { this.timekeeperFinished.get(10, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.warn("Failed to shut down the timekeeper thread for 10 seconds. This is a bug."); } // Once the main timer thread is dead, then notify the caller by rethrowing the exception log.warn("Transport failed to wait for silence: ", t); throw t; } } /** * Start the transport, if it hasn't already started */ @Override public void start() { synchronized (timekeeper) { if (!timekeeper.isAlive() && this.isAlive) { timekeeper.start(); } } } /** * Stop this transport. */ @Override public void stop() { try { // Kill scheduled tasks transportMockTimer.cancel(); // Short-circuit to prevent double closing if (!isAlive || !timekeeper.isAlive()) { return; } // Wait for liveness waitForSilence(); // Kill liveness this.isAlive = false; // Wait for the main thread to die try { this.timekeeperFinished.get(10, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.error("Failed to shut down the timekeeper thread for 10 seconds. This is a bug."); } } finally { // Clear the singleton singleton = null; } } /** {@inheritDoc} */ @Override public boolean threadsCanBlock() { return true; } /** {@inheritDoc} */ @Override protected void finalize() throws Throwable { super.finalize(); stop(); } /** {@inheritDoc} */ @Override public void bind(RaftAlgorithm listener) { // note: don't mock exceptions here. It's just a pain in the butt... Lock writeLock = nodesLock.writeLock(); try { writeLock.lock(); if (!this.nodes.contains(listener)) { this.nodes.add(listener); } } finally { writeLock.unlock(); } } /** {@inheritDoc} */ @Override public Collection<RaftAlgorithm> boundAlgorithms() { Lock readLock = nodesLock.readLock(); try { readLock.lock(); return new ArrayList<>(this.nodes); } finally { readLock.unlock(); } } /** {@inheritDoc} */ @Override public Span expectedNetworkDelay() { return new Span(delayMin, delayMax); } private TransportMessage sendMessage(String sender, String destination, EloquentRaftProto.RaftMessage message, Optional<Long> correlationId) { assert ConcurrencyUtils.ensureNoLocksHeld(); TransportMessage m; //noinspection OptionalIsPresent if (correlationId.isPresent()) { m = new TransportMessage(nextMessageId.incrementAndGet(), correlationId.get(), sender, destination, message.toByteArray()); } else { m = new TransportMessage(nextMessageId.incrementAndGet(), sender, destination, message.toByteArray()); } long transportDelay = sampleDelay(); // We need to hold the transport timer lock while doing this, because otherwise time can slip between computing if // we should drop the packet and adding it to the schedule. transportMockTimer.withTimerLock(() -> { if (shouldDrop(sender, destination, transportDelay)) { log.trace("[{}] Dropped RPC {} -> {}; with delay {}", now(), sender, destination, transportDelay); } else { log.trace("[{}] Sending {} -> {}; with delay {}", now(), sender, destination, transportDelay); numRPCsSent += 1; SafeTimerTask messageDelivery = new SafeTimerTask() { @Override public void runUnsafe() { receiveMessage(m, now()); } }; transportMockTimer.schedule(messageDelivery, transportDelay); } }); // Ensure the timekeeper thread is alive synchronized (timekeeper) { if (!timekeeper.isAlive() && this.isAlive) { timekeeper.start(); } } return m; } /** {@inheritDoc} */ @Override public void rpcTransport(String sender, String destination, EloquentRaftProto.RaftMessage message, Consumer<EloquentRaftProto.RaftMessage> onResponseReceived, Runnable onTimeout, long timeout) { assert ConcurrencyUtils.ensureNoLocksHeld(); TransportMessage m = sendMessage(sender, destination, message, Optional.empty()); WaitingCallback waitingCallback = new WaitingCallback(m.id, onResponseReceived, onTimeout, now() + timeout); synchronized (waitingCallbacks) { waitingCallbacks.add(waitingCallback); } transportMockTimer.schedule(new SafeTimerTask() { @Override public void runUnsafe() { boolean doTimeout = false; synchronized (waitingCallback) { if (waitingCallbacks.contains(waitingCallback)) { waitingCallbacks.remove(waitingCallback); doTimeout = true; } } if (doTimeout) { log.info("Timing out RPC for message {} from {} -> {}", m.id, sender, destination); onTimeout.run(); } } }, timeout); } /** {@inheritDoc} */ @Override public void sendTransport(String sender, String destination, EloquentRaftProto.RaftMessage message) { assert ConcurrencyUtils.ensureNoLocksHeld(); sendMessage(sender, destination, message, Optional.empty()); } /** {@inheritDoc} */ @Override public void broadcastTransport(String sender, EloquentRaftProto.RaftMessage message) { assert ConcurrencyUtils.ensureNoLocksHeld(); assert this.boundAlgorithms().stream().allMatch(x -> x.getClass().getName().contains("RecordingRaft")) || this.boundAlgorithms().stream().filter(x -> x.serverName().equals(sender)).findFirst().map(x -> x.state().leadership != RaftState.LeadershipStatus.OTHER).orElse(false) : "A follower / shadow should not be broadcasting on the transport!"; Lock nodesReadLock = this.nodesLock.readLock(); try { nodesReadLock.lock(); for (RaftAlgorithm target : this.nodes) { String destination = target.serverName(); if (!Objects.equals(target.serverName(), sender)) { sendMessage(sender, destination, message, Optional.empty()); } } } finally { nodesReadLock.unlock(); } } /** * Checks that there are no errors on this transport in the course of operation. * * @return this object, to allow for chaining methods. */ public LocalTransport assertNoErrors() { // (no exceptions on transport) assert exceptions.isEmpty() : "Got " + exceptions.size() + " exceptions on transport. First one: <" + exceptions.get(0).getClass() + ": " + exceptions.get(0).getMessage() + ">"; // (return ok) return this; } /** * This checks several invariants across all the Raft nodes attached to the LocalTransport. If any invariant fails, * this will throw an assert and fail. * * These invariants are from page 14 of Diego's thesis. */ public void assertInvariantsHold() { Lock nodesReadLock = this.nodesLock.readLock(); try { nodesReadLock.lock(); // Election Safety: // At most one leader can be elected in a given term. Set<Long> leaderTerms = new HashSet<>(); for (RaftAlgorithm node : nodes) { if (node.state().isLeader()) { assert(!leaderTerms.contains(node.mutableState().currentTerm)) : "At most one leader can be elected in a given term. More than one leader for term "+node.state().currentTerm; leaderTerms.add(node.mutableState().currentTerm); } } // Leader Append-Only: // A leader never overwrites or deletes entries in its log; it only appends new entries. // TODO: unsure how to verify this from here // Log Matching: // If two logs contain an entry with the same index and term, then the logs are identical in all entries up through // the given index. for (int i = 0; i < nodes.size() - 1; i++) { RaftLog log1 = nodes.get(i).mutableState().log; for (int j = i+1; j < nodes.size(); j++) { RaftLog log2 = nodes.get(j).mutableState().log; long maxSharedIndex = Math.min(log1.getLastEntryIndex(), log2.getLastEntryIndex()); boolean haveAgreedOnIndexAndTerm = false; for (long index = maxSharedIndex; index >= 0; index --) { Optional<Long> log1Term = log1.getPreviousEntryTerm(index); Optional<Long> log2Term = log2.getPreviousEntryTerm(index); if (log1Term.isPresent() && log2Term.isPresent()) { if (log1Term.get().equals(log2Term.get())) { haveAgreedOnIndexAndTerm = true; } else { assert(!haveAgreedOnIndexAndTerm) : "If two logs contain an entry with the same index and term, then the logs are identical in all entries up through the given index. Violation at index "+index; } } else break; } } } // Leader Completeness: // If a log entry is committed in a given term, then that entry will be present in the logs of the leaders for all // higher-numbered terms // TODO: unsure how to verify this from here // State Machine Safety: // If any server has applied a log entry at a given index, then no other server will ever apply a different log // entry for the same index. for (int i = 0; i < nodes.size() - 1; i++) { RaftLog log1 = nodes.get(i).mutableState().log; for (int j = i+1; j < nodes.size(); j++) { RaftLog log2 = nodes.get(j).mutableState().log; // Check non-compacted log entries long maxSharedIndex = Math.min(log1.getLastEntryIndex(), log2.getLastEntryIndex()); for (long index = maxSharedIndex; index >= 0; index --) { Optional<EloquentRaftProto.LogEntry> log1Entry = log1.getEntryAtIndex(index); Optional<EloquentRaftProto.LogEntry> log2Entry = log2.getEntryAtIndex(index); if (log1Entry.isPresent() && log2Entry.isPresent()) { if (log1Entry.get().getTerm() == log2Entry.get().getTerm()) { assert(log1Entry.get().toByteString().equals(log2Entry.get().toByteString())) : "Two log entries at the same index with the same term should be identical"; } } else break; } } } } finally { nodesReadLock.unlock(); } } /** * The current time on the transport. */ public void schedule(long interval, int count, Consumer<Long> task) { SafeTimerTask safeTask = new SafeTimerTask() { @Override public void runUnsafe() throws Throwable { task.accept(now()); } }; // Ensure time doesn't slip while we schedule all of these transportMockTimer.withTimerLock(() -> { for (int i = 0; i < count; ++i) { long targetDelay = interval * (i + 1); transportMockTimer.schedule(safeTask, targetDelay); } }); synchronized (timekeeper) { if (!timekeeper.isAlive() && this.isAlive) { timekeeper.start(); } } } /** * Create a nework partition of the given nodes, separating them from the rest of the cluster * (but allowing them to talk to each other just fine). * * @param fromMillis The time at which to install the network partition. * @param toMillis The time at which to lift the network partition. * @param nodeNames The names of the nodes forming the new partition. These can talk to each other, * but cannot talk to anyone else in the cluster (or visa versa). */ public void partitionOff(long fromMillis, long toMillis, String... nodeNames) { partitions.add(new Partition(fromMillis, toMillis, nodeNames)); } /** * Lift all of our network partitions. */ public void liftPartitions() { partitions.clear(); } /** {@inheritDoc} */ @Override public long now() { if (this.trueTime) { return System.currentTimeMillis(); } else { return transportMockTimer.now(); } } /** Sleep for the given number of milliseconds. This is purely for mocking for tests. */ @Override public void sleep(long millis) { AtomicBoolean slept = new AtomicBoolean(false); // Wait for the given time to arrive schedule(millis, 1, now -> { synchronized (slept) { slept.set(true); slept.notifyAll(); } }); // Wake up the thread synchronized (slept) { while (!slept.get() && isAlive) { try { slept.wait(1000); } catch (InterruptedException ignored) {} } } } /** Schedule an event on the transport's time. */ @SuppressWarnings("ConstantConditions") @Override public void scheduleAtFixedRate(SafeTimerTask task, long period) { task.run(Optional.empty()); transportMockTimer.schedule(task, 0, period); } /** Schedule an event on the transport's time. */ @SuppressWarnings("ConstantConditions") @Override public void schedule(SafeTimerTask task, long delay) { schedule(delay, 1, now -> task.run(Optional.empty())); } /** {@inheritDoc} */ @Override public <E> E getFuture(CompletableFuture<E> future, Duration timeout) throws InterruptedException, ExecutionException, TimeoutException { long millisSlept = 0; while (!future.isDone() && !future.isCancelled() && !future.isCompletedExceptionally()) { sleep(1); if (Thread.interrupted()) { throw new InterruptedException(); } millisSlept += 1; if (millisSlept > timeout.toMillis()) { throw new TimeoutException("Took too long to return future"); } } if (future.isCompletedExceptionally()) { Throwable exception = (Throwable) future.exceptionally(ex -> (E) ex).get(); throw new ExecutionException(exception); } E result = future.getNow(null); if (result == null) { throw new IllegalStateException("Logic error in future resolution"); } return result; } /** * If true, this packet is destined destination be dropped. * This can happen either sender random network failures (see {@link #dropProb}), * or if there's a partition in place at the delivery time (see {@link #partitions}). * * @param sender The source server. * @param destination The server we're sending destination. * @param delay The time at which this packet is intended destination arrive at its destination. * * @return True if we should drop the packet. */ private boolean shouldDrop(String sender, String destination, long delay) { // 1. Resolve partitions Iterator<Partition> partitions = this.partitions.iterator(); long deliveryTime = now() + delay; while (partitions.hasNext()) { Partition partition = partitions.next(); if (partition.endTime < now()) { partitions.remove(); // some cleanup } else if (partition.startTime <= deliveryTime && partition.endTime > deliveryTime) { // Case: this partition is active if (( partition.members.contains(sender) && !partition.members.contains(destination)) || (!partition.members.contains(sender) && partition.members.contains(destination)) ) { // Case: the packet crosses the partition -- drop it return true; } } } // 2. Resolve random packet drops //noinspection RedundantIfStatement if (rand.nextDouble() < dropProb) { // Case: randomly dropping return true; } // Default: the packet goes through happily return false; } /** * Sample a delay from the delay distribution. * This is some value between {@link #delayMin} and {@link #delayMax}, with * a bias towards {@link #delayMin} plus some epsilon (currently, 10ms). */ private long sampleDelay() { if (delayMin == delayMax) { // Case: we're running on a deterministic delay return delayMin; } else if (rand.nextDouble() < 0.1) { // Case: we're hit an unusually long delay return delayMin + rand.nextInt((int) (delayMax - delayMin)); } else { // Case: we've hit our usual delay range return delayMin + rand.nextInt((int) (Math.min(delayMax, delayMin + 10) - delayMin)); } } /** * Receive a message, and handle the message. * This is called by the events scheduled on the main mock timer thread. * * @param message The received message. * @param now The current time. This is mostly for a consistency check -- time should not * move while we are in this function. */ private void receiveMessage(TransportMessage message, long now) { List<WaitingCallback> toRun = new ArrayList<>(); synchronized (waitingCallbacks) { Set<WaitingCallback> toDelete = new IdentityHashSet<>(); try { for (WaitingCallback callbackCandidate : waitingCallbacks) { if (callbackCandidate.messageId == message.correlationId) { // 3.3.1. Case: this is an RPC reply log.trace("[{}] {} received RPC reply from {} at time {}; id={} correlation_id={}", now, message.target, message.sender, now, message.id, message.correlationId); toRun.add(callbackCandidate); toDelete.add(callbackCandidate); } } } finally { waitingCallbacks.removeAll(toDelete); // clean up callbacks } } if (!toRun.isEmpty()) { for (WaitingCallback callback : toRun) { try { callback.onSuccess.accept(EloquentRaftProto.RaftMessage.parseFrom(message.contents)); } catch (InvalidProtocolBufferException e) { log.warn("Transport got a bad protocol buffer; logging in exceptions", e); exceptions.add(e); } } return; } // 3.3.2. Case: this is not an RPC reply log.trace("[{}] {} received message from {}; id={} correlation_id={}", now(), message.target, message.sender, message.id, message.correlationId); if (message.correlationId >= 0) { synchronized (waitingCallbacks) { log.trace("[{}] Above message (id={}) has an unmatched correlation_id (corr_id={}). waitingCallbacks={}", now(), message.id, message.correlationId, waitingCallbacks); } } try { List<RaftAlgorithm> nodes = new ArrayList<>(); Lock nodesReadLock = nodesLock.readLock(); try { nodesReadLock.lock(); nodes.addAll(this.nodes); } finally { nodesReadLock.unlock(); } // 1. Parse the message EloquentRaftProto.RaftMessage request; try { request = EloquentRaftProto.RaftMessage.parseFrom(message.contents); } catch (InvalidProtocolBufferException e) { log.warn("Could not decode message {}; adding to exception list", message); this.exceptions.add(e); return; } // 2. Broadcast the message to the nodes // 2.1. Check that the destination is valid if (nodes.stream().noneMatch(node -> Objects.equals(message.target, node.serverName()))) { log.warn("Server {} was not found in server list {}", message.target, this.nodes.stream().map(RaftAlgorithm::serverName).collect(Collectors.toSet())); } // 2.2. Deliver the message nodes.stream() .filter(node -> Objects.equals(message.target, node.serverName())) .findAny() .ifPresent(node -> { Optional<RaftLifecycle> lifecycle = node.lifecycle(); if (lifecycle.isPresent() && lifecycle.get().CORE_THREAD_POOLS_CLOSED.get()) { log.trace("Not delivering messages to "+node.serverName()+" because core thread pools are already closed"); return; } if (request.getIsRPC()) { // 2.2.1. Case: this is a blocking RPC CompletableFuture<EloquentRaftProto.RaftMessage> response = node.receiveRPC(request, now); if (response == null) { NullPointerException exception = new NullPointerException(); log.warn("Got null response from RPC: ", exception); exceptions.add(exception); return; } assert now() == now : "Time should not be slipping"; response.whenComplete((reply, e) -> { // (this is an RPC response, which is special because it has a correlation id) if (e != null) { log.warn("Got exception from RPC: ", e); } sendMessage(message.target, message.sender, reply, Optional.of(message.id)); }); } else { // 2.2.2. Case: this is a non-blocking message node.receiveMessage(request, (proto) -> sendTransport(message.target, message.sender, proto), now); } }); } catch (Throwable t) { log.warn("Caught exception on receiving message: ", t); exceptions.add(t); } } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/NetRaftTransport.java
package ai.eloquent.raft; import ai.eloquent.data.UDPBroadcastProtos; import ai.eloquent.data.UDPTransport; import ai.eloquent.util.ConcurrencyUtils; import ai.eloquent.util.IdentityHashSet; import ai.eloquent.util.SafeTimerTask; import ai.eloquent.util.Span; import com.google.protobuf.InvalidProtocolBufferException; import io.grpc.*; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.*; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; /** * A Raft transport implemented directly over UDP * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class NetRaftTransport implements RaftTransport { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(NetRaftTransport.class); /** * The port we are listening to RPC messages on. */ private static final int DEFAULT_RPC_LISTEN_PORT = 42889; /** * The name we should assign ourselves on the transport. */ public final String serverName; /** * If true, run the handling of messages on the transport in a new thread. */ public final boolean thread; /** * The set of algorithms bound to this transport, so that we don't * add the same algorithm twice. */ private final Set<RaftAlgorithm> boundAlgorithms = new IdentityHashSet<>(); /** * The port we are listening to RPC messages on. */ private final int rpcListenPort; /** * A map from destination address to a gRPC managed channel for that destination. */ private final Map<String, ManagedChannel> channel = new HashMap<>(); /** * Create a UDP transport. * * @param serverName The name of our server * @param rpcListenPort The gRPC port to listen on. * @param async If true, run messages on the transport in separate threads. * * @throws UnknownHostException Thrown if we could not get our own hostname. */ public NetRaftTransport(String serverName, int rpcListenPort, boolean async) throws IOException { // Save some trivial variables this.serverName = serverName; this.rpcListenPort = rpcListenPort; this.thread = async; // Assertions if (!serverName.matches("[12]?[0-9]?[0-9]\\.[12]?[0-9]?[0-9]\\.[12]?[0-9]?[0-9]\\.[12]?[0-9]?[0-9](_.*)?")) { throw new IllegalArgumentException("Invalid server name \""+serverName+"\". Server name must start with an IPv4 address, followed by an optional underscore and custom descriptor. For example, \"127.0.0.1_foobar\"."); } // Start the Grpc Server ServerBuilder .forPort(rpcListenPort) .addService(new RaftGrpc.RaftImplBase() { @Override public void rpc(EloquentRaftProto.RaftMessage request, StreamObserver<EloquentRaftProto.RaftMessage> responseObserver) { log.trace("Got an RPC request"); try { UDPTransport.DEFAULT.get().doAction(async, "handle inbound RPC", () -> { for (RaftAlgorithm listener : boundAlgorithms) { listener.receiveRPC(request, now()).whenComplete((EloquentRaftProto.RaftMessage response, Throwable exception) -> { if (exception != null || response == null) { responseObserver.onError(exception == null ? new RuntimeException() : exception); } else { responseObserver.onNext(response); responseObserver.onCompleted(); } }); } }); } catch (Throwable t) { responseObserver.onError(t); } } }) .build() .start(); } /** @see #NetRaftTransport(String, int, boolean) */ public NetRaftTransport(String serverName) throws IOException { this(serverName, DEFAULT_RPC_LISTEN_PORT, false); } /** {@inheritDoc} */ @Override public void scheduleAtFixedRate(SafeTimerTask timerTask, long period) { RaftLifecycle.global.timer.get().scheduleAtFixedRate(timerTask, 0L, period); } /** {@inheritDoc} */ @Override public void schedule(SafeTimerTask timerTask, long delay) { RaftLifecycle.global.timer.get().schedule(timerTask, delay); } /** {@inheritDoc} */ @Override public synchronized void bind(RaftAlgorithm listener) { if (!boundAlgorithms.contains(listener)) { // Bind ourselves to UDP UDPTransport.DEFAULT.get().bind(UDPBroadcastProtos.MessageType.RAFT, data -> { log.trace("Received a UDP message"); try { EloquentRaftProto.RaftMessage message = EloquentRaftProto.RaftMessage.parseFrom(data); if (!message.getSender().equals(this.serverName)) { // don't send ourselves messages assert ConcurrencyUtils.ensureNoLocksHeld(); listener.receiveMessage(message, reply -> sendTransport(listener.serverName(), message.getSender(), reply), now()); } } catch (InvalidProtocolBufferException e) { log.warn("Not a Raft message: ", e); } }); // Register that we're bound (this binds to gRPC) boundAlgorithms.add(listener); } } /** {@inheritDoc} */ @Override public Collection<RaftAlgorithm> boundAlgorithms() { return this.boundAlgorithms; } /** {@inheritDoc} */ @Override public void rpcTransport(String sender, String destination, EloquentRaftProto.RaftMessage message, Consumer<EloquentRaftProto.RaftMessage> onResponseReceived, Runnable onTimeout, long timeout) { assert ConcurrencyUtils.ensureNoLocksHeld(); // Get the destination IP address int underscoreIndex; final String destinationIp; if ((underscoreIndex = destination.indexOf("_")) > 0) { destinationIp = destination.substring(0, underscoreIndex); } else { destinationIp = destination; } ManagedChannel channel; synchronized (this) { // Clear old entries for (Map.Entry<String, ManagedChannel> entry : new HashSet<>(this.channel.entrySet())) { if (entry.getValue().isTerminated() || entry.getValue().isShutdown()) { entry.getValue().shutdown(); this.channel.remove(entry.getKey()); } } // Get our channel channel = this.channel.computeIfAbsent(destination, name -> ManagedChannelBuilder.forAddress(destinationIp, rpcListenPort) .usePlaintext() .build()); } // Call our stub AtomicBoolean awaitingResponse = new AtomicBoolean(true); log.trace("Sending RPC request to {} @ ip {}", destination, destinationIp); RaftGrpc.newStub(channel) .withDeadlineAfter(timeout, TimeUnit.MILLISECONDS) .rpc(message, new StreamObserver<EloquentRaftProto.RaftMessage>() { @Override public void onNext(EloquentRaftProto.RaftMessage value) { log.trace("Got an RPC response from {}", destinationIp); if (awaitingResponse.getAndSet(false)) { assert ConcurrencyUtils.ensureNoLocksHeld(); onResponseReceived.accept(value); } } @Override public void onError(Throwable t) { if (awaitingResponse.getAndSet(false)) { assert ConcurrencyUtils.ensureNoLocksHeld(); onTimeout.run(); } } @Override public void onCompleted() { if (awaitingResponse.getAndSet(false)) { assert ConcurrencyUtils.ensureNoLocksHeld(); onTimeout.run(); } } }); } /** {@inheritDoc} */ @Override public void sendTransport(String sender, String destination, EloquentRaftProto.RaftMessage message) { log.trace("Sending a UDP message to {}", destination); assert ConcurrencyUtils.ensureNoLocksHeld(); // Get the destination IP address int underscoreIndex; final String destinationIp; if ((underscoreIndex = destination.indexOf("_")) > 0) { destinationIp = destination.substring(0, underscoreIndex); } else { destinationIp = destination; } // SEnd the message UDPTransport.DEFAULT.get().sendTransport(destinationIp, UDPBroadcastProtos.MessageType.RAFT, message.toByteArray()); } /** {@inheritDoc} */ @Override public void broadcastTransport(String sender, EloquentRaftProto.RaftMessage message) { log.trace("Broadcasting a UDP message"); assert ConcurrencyUtils.ensureNoLocksHeld(); UDPTransport.DEFAULT.get().broadcastTransport(UDPBroadcastProtos.MessageType.RAFT, message.toByteArray()); } /** {@inheritDoc} */ @Override public Span expectedNetworkDelay() { return new Span(10, 100); } /** {@inheritDoc} */ @Override public String toString() { return "Raft:" + UDPTransport.DEFAULT.get().toString(); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/RaftAlgorithm.java
package ai.eloquent.raft; import java.util.Collections; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import ai.eloquent.monitoring.Prometheus; import ai.eloquent.raft.EloquentRaftProto.*; import ai.eloquent.util.Span; import ai.eloquent.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A simple little interface for receiving Raft RPC messages. * This is also, in effect, the implementation of the Raft protocol. */ public interface RaftAlgorithm { /** * An SLF4J Logger for this class. */ Logger log = LoggerFactory.getLogger(RaftAlgorithm.class); /** * Timing statistics for Raft. */ Object summaryTiming = Prometheus.summaryBuild("raft", "Statistics on the Raft RPC calls", "rpc"); /** * Receive a non-blocking RPC in the form of a {@link ai.eloquent.raft.EloquentRaftProto.RaftMessage} proto. * * @param messageProto The {@link ai.eloquent.raft.EloquentRaftProto.RaftMessage} we have received. * @param replySender A callback for sending a message to the sender on the underlying transport. * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. */ @SuppressWarnings("Duplicates") default void receiveMessage(EloquentRaftProto.RaftMessage messageProto, Consumer<EloquentRaftProto.RaftMessage> replySender, long now) { if (!messageProto.getAppendEntries().equals(AppendEntriesRequest.getDefaultInstance())) { // Append Entries Object timerStart = Prometheus.startTimer(summaryTiming,"append_entries"); receiveAppendEntriesRPC(messageProto.getAppendEntries(), msg -> { Prometheus.observeDuration(timerStart); replySender.accept(msg); }, now); } else if (!messageProto.getRequestVotes().equals(RequestVoteRequest.getDefaultInstance())) { // Request Votes Object timerStart = Prometheus.startTimer(summaryTiming,"request_votes"); receiveRequestVoteRPC(messageProto.getRequestVotes(), msg -> { Prometheus.observeDuration(timerStart); replySender.accept(msg); }, now); } else if (!messageProto.getInstallSnapshot().equals(InstallSnapshotRequest.getDefaultInstance())) { // Install Snapshot Object timerStart = Prometheus.startTimer(summaryTiming,"install_snapshot"); receiveInstallSnapshotRPC(messageProto.getInstallSnapshot(), msg -> { Prometheus.observeDuration(timerStart); replySender.accept(msg); }, now); } else if (!messageProto.getAppendEntriesReply().equals(AppendEntriesReply.getDefaultInstance())) { // REPLY Append Entries Object timerStart = Prometheus.startTimer(summaryTiming,"append_entries_reply"); try { receiveAppendEntriesReply(messageProto.getAppendEntriesReply(), now); } finally { Prometheus.observeDuration(timerStart); } } else if (!messageProto.getRequestVotesReply().equals(RequestVoteReply.getDefaultInstance())) { // REPLY Request Votes Object timerStart = Prometheus.startTimer(summaryTiming,"request_votes_reply"); try { receiveRequestVotesReply(messageProto.getRequestVotesReply(), now); } finally { Prometheus.observeDuration(timerStart); } } else if (!messageProto.getInstallSnapshotReply().equals(InstallSnapshotReply.getDefaultInstance())) { // REPLY Install Snapshot Object timerStart = Prometheus.startTimer(summaryTiming,"installl_snapshot_reply"); try { receiveInstallSnapshotReply(messageProto.getInstallSnapshotReply(), now); } finally { Prometheus.observeDuration(timerStart); } } else if (!messageProto.getAddServer().equals(AddServerRequest.getDefaultInstance())) { // Add Server Object timerStart = Prometheus.startTimer(summaryTiming,"add_server"); CompletableFuture<RaftMessage> future = receiveAddServerRPC(messageProto.getAddServer(), now); future.whenComplete( (reply, exception) -> { Prometheus.observeDuration(timerStart); if (exception != null && reply != null) { replySender.accept(reply); } else { replySender.accept(null); } }); } else if (!messageProto.getRemoveServer().equals(RemoveServerRequest.getDefaultInstance())) { // Remove Server Object timerStart = Prometheus.startTimer(summaryTiming,"remove_server"); CompletableFuture<RaftMessage> future = receiveRemoveServerRPC(messageProto.getRemoveServer(), now); future.whenComplete( (reply, exception) -> { Prometheus.observeDuration(timerStart); if (exception != null && reply != null) { replySender.accept(reply); } else { replySender.accept(null); } }); } else if (!messageProto.getApplyTransition().equals(ApplyTransitionRequest.getDefaultInstance())) { // Apply Transition Object timerStart = Prometheus.startTimer(summaryTiming,"apply_transition"); CompletableFuture<RaftMessage> future = receiveApplyTransitionRPC(messageProto.getApplyTransition(), now); future.whenComplete( (reply, exception) -> { Prometheus.observeDuration(timerStart); if (exception != null && reply != null) { replySender.accept(reply); } else { replySender.accept(null); } }); } else { receiveBadRequest(messageProto); } } /** * Receive a blocking RPC in the form of a {@link ai.eloquent.raft.EloquentRaftProto.RaftMessage} proto. * This function will return a {@link CompletableFuture} that is completed when the RPC completes. * * @param messageProto The {@link ai.eloquent.raft.EloquentRaftProto.RaftMessage} we have received. * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. * * @return A {@link CompletableFuture} that completes when the RPC completes. */ default CompletableFuture<EloquentRaftProto.RaftMessage> receiveRPC(EloquentRaftProto.RaftMessage messageProto, long now) { Object timerStart = null; CompletableFuture<EloquentRaftProto.RaftMessage> future = new CompletableFuture<>(); try { if (messageProto.getAppendEntries() != AppendEntriesRequest.getDefaultInstance()) { // Append Entries timerStart = Prometheus.startTimer(summaryTiming, "append_entries_rpc"); receiveAppendEntriesRPC(messageProto.getAppendEntries(), future::complete, now); } else if (messageProto.getRequestVotes() != RequestVoteRequest.getDefaultInstance()) { // Request Votes timerStart = Prometheus.startTimer(summaryTiming, "request_votes_rpc"); receiveRequestVoteRPC(messageProto.getRequestVotes(), future::complete, now); } else if (messageProto.getInstallSnapshot() != InstallSnapshotRequest.getDefaultInstance()) { // Install Snapshot timerStart = Prometheus.startTimer(summaryTiming, "install_snapshop_rpc"); receiveInstallSnapshotRPC(messageProto.getInstallSnapshot(), future::complete, now); } else if (messageProto.getAddServer() != AddServerRequest.getDefaultInstance()) { // Add Server timerStart = Prometheus.startTimer(summaryTiming, "add_server_rpc"); future = receiveAddServerRPC(messageProto.getAddServer(), now); } else if (messageProto.getRemoveServer() != RemoveServerRequest.getDefaultInstance()) { // Remove Server timerStart = Prometheus.startTimer(summaryTiming, "remove_server_rpc"); future = receiveRemoveServerRPC(messageProto.getRemoveServer(), now); } else if (messageProto.getApplyTransition() != ApplyTransitionRequest.getDefaultInstance()) { // Apply Transition timerStart = Prometheus.startTimer(summaryTiming, "transition_rpc"); future = receiveApplyTransitionRPC(messageProto.getApplyTransition(), now); } else { timerStart = Prometheus.startTimer(summaryTiming, "unknown_rpc"); future.completeExceptionally(new IllegalStateException("Message type not implemented: " + messageProto)); } } catch (Throwable t) { future.completeExceptionally(t); } Object timerStartFinal = timerStart; return future.thenApply(x -> { if (timerStartFinal != null) { Prometheus.observeDuration(timerStartFinal); } return x; }); } /** * get A COPY OF the current Raft state. */ RaftState state(); /** * DANGEROUS: USE ONLY IF YOU KNOW WHAT YOU ARE DOING * * get A REFERENCE TO the current Raft state. */ RaftState mutableState(); /** * DANGEROUS: USE ONLY IF YOU KNOW WHAT YOU ARE DOING * * get A REFERENCE TO the current Raft state machine. */ RaftStateMachine mutableStateMachine(); /** * The term this node sees. This should simply return {@link RaftState#currentTerm} */ long term(); /** * The name of this server. This should simply return {@link RaftState#serverName} */ String serverName(); // // -------------------------------------------------------------------------- // APPEND ENTRIES RPC // -------------------------------------------------------------------------- // /** * Send out an append entries RPC (i.e., a heartbeat) to all listeners on the transport. * * @param now The current time. This is usually {@link System#currentTimeMillis()}, but can * be mocked by unit tests. */ void broadcastAppendEntries(long now); /** * Send an append entries request to a particular server. * * @param target The server we're sending the append entries RPC to. * @param nextIndex The nextIndex value on the target machine. */ void sendAppendEntries(String target, long nextIndex); /** * Receive a request to apply a transition or multiple transitions. * <b>This also doubles as the heartbeat for the server.</b> * There are three cases here: * * <ol> * <li><b>If the node is an Oligarch:</b> The node should respond to the heartbeat.</li> * <li><b>If the node is a Shadow and the Oligarchy is full:</b> The node should apply the transition * and not reply.</li> * <li><b>If the node is a Shadow and the Oligarchy is not full:</b> The node should apply the transition * and respond to the heartbeat.</li> * </ol> * * @param heartbeat The request body, doubling both as a heartbeat and a request to mutate the * state machine. * @param replyLeader The method for replying to the leader with an ACK of the request. * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. */ void receiveAppendEntriesRPC(EloquentRaftProto.AppendEntriesRequest heartbeat, Consumer<EloquentRaftProto.RaftMessage> replyLeader, long now); /** * We received an asynchronous heartbeat from a server. * This function is called to handle that heartbeat reply. * * @param reply The heartbeat ACK from the follower node. * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. */ void receiveAppendEntriesReply(EloquentRaftProto.AppendEntriesReply reply, long now); // // -------------------------------------------------------------------------- // INSTALL SNAPSHOT RPC // -------------------------------------------------------------------------- // /** * Receive a snapshot request RPC call. * This should install a snapshot, and does not have to issue a response. * * @param snapshot The snapshot to install. * @param replyLeader The method for replying to the leader with an ACK of the request. * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. */ void receiveInstallSnapshotRPC(InstallSnapshotRequest snapshot, Consumer<RaftMessage> replyLeader, long now); /** * We received an asynchronous snapshot reply from a server. * * @param reply The snapshot reply from the follower node. * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. */ void receiveInstallSnapshotReply(EloquentRaftProto.InstallSnapshotReply reply, long now); // // -------------------------------------------------------------------------- // ELECTIONS // -------------------------------------------------------------------------- // /** * Signal to the cluster that we are a candidate for an election, and we are soliciting votes */ void triggerElection(long now); /** * Clearly an election has been initiated, and some candidate is requesting votes to become the new leader. * This <b>must</b> be responded to both by Oligarch and Shadow nodes. * * @param voteRequest The request for votes for a particular server. * @param replyLeader The method for replying to the leader with an ACK of the request. * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. */ void receiveRequestVoteRPC(EloquentRaftProto.RequestVoteRequest voteRequest, Consumer<EloquentRaftProto.RaftMessage> replyLeader, long now); /** * We received votes from another server. * * @param reply The vote from the server, which we should count to see if we have a * majority. * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. */ void receiveRequestVotesReply(EloquentRaftProto.RequestVoteReply reply, long now); // // -------------------------------------------------------------------------- // CLUSTER MEMBERSHIP // -------------------------------------------------------------------------- // /** * <p> * A request has been received to add a server to the cluster. * This is only well-defined for the leader -- if the request was not received by the leader, * then it should forward to the leader. * </p> * * <p> * The algorithm for this is the following: * </p> * * <ol> * <li> Reply NOT_LEADER if not leader (in practice, we forward it to the leader).</li> * <li> Catch up server for a fixed number of rounds. Reply TIMEOUT if a server does not make progress for an election * timeout or if the last round takes longer than the election timeout.</li> * <li> Wait until previous configuration in log is committed.</li> * <li> Append a new configuration entry to the log, (old configuration plus new server), commit it using a majority of * the new configuration.</li> * <li> Reply OK.</li> * </ol> * * @param addServerRequest The request to add the server. * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. * * @return the RPC response, as a future. */ CompletableFuture<RaftMessage> receiveAddServerRPC(AddServerRequest addServerRequest, long now); /** * A request has been received to remove a server to the cluster. * This is only well-defined for the leader -- if the request was not received by the leader, * then it should forward to the leader. * * @param removeServerRequest The snapshot to install. * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. * * @return the RPC response, as a future. */ CompletableFuture<RaftMessage> receiveRemoveServerRPC(RemoveServerRequest removeServerRequest, long now); // // -------------------------------------------------------------------------- // CONTROL // -------------------------------------------------------------------------- // /** * Apply a transition to Raft. * * @param transition The transition to apply * @param now The timestamp of the current time. In non-mock cases, this is always {@link System#currentTimeMillis()}. */ CompletableFuture<RaftMessage> receiveApplyTransitionRPC(EloquentRaftProto.ApplyTransitionRequest transition, long now); /** * Mark this node for bootstrapping. This should just be an alias for {@link RaftState#bootstrap(boolean)}, with * some error checks beforehand. * If this node cannot bootstrap, we return false. * * @return True if we could bootstrap this node. */ boolean bootstrap(boolean force); /** * A method, called primarily from unit tests, to stop this algorithm and clean up the underlying transport, * if appropriate. * An empty implementation is OK if there's nothing to stop. * * @param kill If true, kill the server unceremoniously, without waiting for a handoff. */ default void stop(boolean kill) {} /** * Check if the algorithm has already been stopped via {@link #stop(boolean)}. */ boolean isRunning(); /** * The interval between heartbeats for this particular Raft node / implementation. * This should be substantially shorter than {@link #electionTimeoutMillisRange()} */ default long heartbeatMillis() { return 50; // by default, 50 millis / heartbeat } /** The default timeout range for elections. */ Span DEFAULT_ELECTION_RANGE = new Span(1000, 2000); /** * The election timeout. * This should be substantially longer than {@link #heartbeatMillis()} */ default Span electionTimeoutMillisRange() { return DEFAULT_ELECTION_RANGE; } /** * A method to be called on every heartbeat interval. * If we're the leader, this sends out heartbeats. * If we're a follower, this ensures that we can trigger the appropriate timeout events. */ void heartbeat(long now); /** * A bad RPC call was received. Signal the error appropriately. * This can happen for two reasons: * * <ol> * <li>The RPC type is not supported.</li> * <li>The proto of the RPC was poorly formatted.</li> * </ol> * * @param message The raw message received. */ void receiveBadRequest(RaftMessage message); /** * Get the RaftLifecycle object that this Algorithm is registered for. */ Optional<RaftLifecycle> lifecycle(); /** * This gets the RaftTransport associated with this RaftAlgorithm. */ RaftTransport getTransport(); /** * Shutdown the argument Raft algorithm, using the time given in the argument transport. * * @param raft The implementing Raft algorithm. * @param transport The transport to run timing on, where necessary. * @param allowClusterDeath If true, allow the cluster to lose state and completely shut down. * Otherwise, we wait for another live node to show up before shutting * down (the default). */ static void shutdown(RaftAlgorithm raft, RaftTransport transport, boolean allowClusterDeath) { // 1. Add ourselves to the hospice log.info("{} - Shutting down Raft", raft.mutableState().serverName); log.info("{} - [{}] Entering the hospice", raft.mutableState().serverName, transport.now()); boolean inHospice = false; int attempts = 0; while (!inHospice && (++attempts) < 50) { try { // 1.1. Try to add ourselves to the hospice RaftMessage response = raft.receiveApplyTransitionRPC(ApplyTransitionRequest.newBuilder() .setNewHospiceMember(raft.serverName()) .build(), transport.now()).get(raft.electionTimeoutMillisRange().end + 100, TimeUnit.MILLISECONDS); inHospice = response.getApplyTransitionReply().getSuccess(); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.info("{} - [{}] Could not apply hospice transition: ", raft.mutableState().serverName, transport.now(), e); } finally { if (!inHospice) { // 1.2. If we failed, wait for an election transport.sleep(raft.electionTimeoutMillisRange().end + 100); } } } if (attempts >= 50) { log.warn("{} - [{}] Could not add ourselves to the hospice; continuing anyways and wishing for the best", raft.mutableState().serverName, transport.now()); } else { log.info("{} - [{}] Entered the hospice", raft.mutableState().serverName, transport.now()); } // 2. Wait for someone else to appear while (!allowClusterDeath && raft.mutableState().log.committedQuorumMembers.size() < 2) { log.warn("{} - [{}] We're the last member of the quorum -- sleeping to wait for someone else to arrive. Errors={}. Heartbeats from={}. Hospice={}.", raft.mutableState().serverName, transport.now(), raft instanceof EloquentRaftAlgorithm ? StringUtils.join(((EloquentRaftAlgorithm) raft).errors(), ", ") : "<n/a>", raft.mutableState().lastMessageTimestamp.orElse(Collections.emptyMap()).keySet(), raft.mutableStateMachine().getHospice() ); transport.sleep(1000); } // 3. Remove ourselves from the cluster log.info("{} - [{}] Removing ourselves from the cluster", raft.mutableState().serverName, transport.now()); boolean inCluster = true; attempts = 0; while (inCluster && (++attempts) < 50) { try { // 3.1. Try to remove ourselves from the cluster RaftMessage response = raft.receiveRemoveServerRPC(RemoveServerRequest.newBuilder() .setOldServer(raft.serverName()) .build(), transport.now()).get(raft.electionTimeoutMillisRange().end + 100, TimeUnit.MILLISECONDS); if (response.getRemoveServerReply().getStatus() == MembershipChangeStatus.OK) { inCluster = false; } } catch (InterruptedException | ExecutionException | TimeoutException e) { log.info("{} - [{}] Could not apply remove server transition: ", raft.mutableState().serverName, transport.now(), e); } finally { attempts += 1; if (inCluster) { // 3.2. If we failed, wait for an election transport.sleep(raft.electionTimeoutMillisRange().end + 100); transport.sleep(raft.electionTimeoutMillisRange().end + 100); } } } if (attempts >= 50) { log.warn("{} - [{}] Could not remove ourselves to the cluster; continuing anyways and wishing for the best", raft.mutableState().serverName, transport.now()); } else { log.info("{} - [{}] Removed ourselves from the cluster", raft.mutableState().serverName, transport.now()); } // 4. Stop the algorithm log.info("{} - [{}] Stopping the algorithm", raft.mutableState().serverName, transport.now()); raft.stop(false); log.info("{} - [{}] Stopped the algorithm", raft.mutableState().serverName, transport.now()); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/RaftBackedCache.java
package ai.eloquent.raft; import ai.eloquent.util.Pointer; import ai.eloquent.util.SafeTimerTask; import ai.eloquent.util.TimerUtils; import com.google.protobuf.InvalidProtocolBufferException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.time.Duration; import java.util.*; import java.util.concurrent.*; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; /** * A cache that keeps values in Raft, but saves them to a given persistence store * when they have been unmodified in Raft for too long. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public abstract class RaftBackedCache<V> implements Iterable<Map.Entry<String,V>>, AutoCloseable { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(RaftBackedCache.class); private static final int DEFAULT_MAX_SIZE_BYTES = 0x1 << 20; // 1MB by default /** * The implementing Raft for the cache. */ public final Theseus raft; /** * This manages evicting elements from the RaftBackedCache. We hold onto a handle so we can cancel() it when we close * the RaftBackedCache. */ private SafeTimerTask evictionTask; /** * This is where we keep all of the listeners that fire whenever the current state changes */ Map<ChangeListener, KeyValueStateMachine.ChangeListener> changeListeners = new IdentityHashMap<>(); /** * Track the owner of a change listener, so we can make sure we close it if needed. */ private final Map<ChangeListener, WeakReference<Object>> changeListenerOwner = new ConcurrentHashMap<>(); /** * This is a single entry in the RaftBackedCache. */ static class Entry<V> implements Map.Entry<String, V> { /** If true, we have persisted this entry since the last time we wrote it locally. */ public boolean isPersisted; public final String key; /** The value of this entry, parameterized by the type of the cache. */ public final V value; /** The straightforward constructor */ Entry(String key, boolean isPersisted, V value) { this.key = key; this.isPersisted = isPersisted; this.value = value; } /** * This deserializes a single entry from its raw bytes. */ public static <V> Entry<V> deserialize(String key, byte[] raw, Function<byte[], Optional<V>> deserialize) throws InvalidProtocolBufferException { byte persistedSinceLastWrite = raw[0]; // TODO:opt if this copy proves to be inefficient, we should replace this with buffers byte[] rest = new byte[raw.length - 1]; System.arraycopy(raw, 1, rest, 0, rest.length); Optional<V> value = deserialize.apply(rest); if (!value.isPresent()) { // TODO: get rid of this in the next version // In order to be backwards compatible, we now back off to reading the raw data, without the prepended flag for // persistence Optional<V> backwardsCompatibleValue = deserialize.apply(raw); if (backwardsCompatibleValue.isPresent()) { return new Entry<>(key, false, backwardsCompatibleValue.get()); } throw new InvalidProtocolBufferException("Deserialization returned Optional.empty()"); } return new Entry<>(key, persistedSinceLastWrite == 1, value.get()); } /** * This does a quick in-place check for whether we've persisted a value, without deserializing the whole thing. * @param raw the serialized value under examination * @return true if we've persisted the value since our last write */ public static boolean readIsPersisted(byte[] raw) { return raw[0] == 1; } /** * This serializes a single entry to its raw bytes, with a header */ public byte[] serialize(Function<V, byte[]> serialize) { byte[] valueSerialized = serialize.apply(value); byte[] complete = new byte[valueSerialized.length + 1]; System.arraycopy(valueSerialized, 0, complete, 1, valueSerialized.length); complete[0] = (byte)(isPersisted ? 1 : 0); return complete; } @Override public String getKey() { return this.key; } @Override public V getValue() { return this.value; } @Override public V setValue(V value) { throw new UnsupportedOperationException(); } } /** * This holds a locally registered callback that will be called whenever the cache changes. This lets code * wait for changes to the cluster, and respond appropriately. */ @FunctionalInterface public interface ChangeListener<V> { /** * Run on a value of the state machine changing. * * @param changedKey The key that changed. * @param newValue The new value of the changed key, or {@link Optional#empty()} if we are removing a key. */ void onChange(String changedKey, Optional<V> newValue); } /** * Run every time an object is set in the cache. * * @param object The object we're setting in the cache. */ protected void onSet(V object) { } /** The number of eviction tasks currently running, to make sure we don't spam the thread */ final Set<CompletableFuture<Boolean>> evictionTasksRunning = ConcurrentHashMap.newKeySet(); /** * Create a Raft backed cache with a particular Raft implementation. */ protected RaftBackedCache(Theseus raft, Duration idleDuration, Duration elementLifetime, int maxSizeBytes) { this.raft = raft; // This task is responsible for saving changes to SQL. It is NOT, however, responsible for removing elements from Raft evictionTask = new SafeTimerTask() { @Override public void runUnsafe() { // Filter our eviction tasks to only include things that aren't done yet evictionTasksRunning.removeAll(evictionTasksRunning.stream().filter(f -> !f.isDone()).collect(Collectors.toList())); // 1. Find keys that have been idle, and write those changes to SQL // DO NOT evict these changes from Raft directly, but instead mark those entries as having been persisted out // since their last write. Set<String> keysToSave = raft.stateMachine.keysIdleSince(idleDuration, raft.node.transport.now()); keysToSave.addAll(raft.stateMachine.keysPresentSince(elementLifetime, raft.node.transport.now())); for (String key : keysToSave) { if (key.startsWith(prefix())) { if (!valuePersistedSinceLastWrite(key)) { // 2. Get a lock on those keys evictionTasksRunning.add(raft.withDistributedLockAsync(key, () -> { // 3. Read the value in Raft Optional<byte[]> valueBytes = raft.getElement(key); if (valueBytes.isPresent()) { // Catch the race condition where someone saves between our reading the value and getting the lock if (Entry.readIsPersisted(valueBytes.get())) return CompletableFuture.completedFuture(true); try { String localKey = key.replace(prefix(), ""); Entry<V> entry = Entry.deserialize(localKey, valueBytes.get(), RaftBackedCache.this::deserialize); try { // 4. Save the value somewhere else log.info("Persisting RaftBackedCache element with key {}" , localKey); persist(localKey, entry.value, false); // Save the fact that we've persisted this key back to raft, so we don't keep hitting SQL entry.isPersisted = true; return raft.setElementAsync(key, entry.serialize(RaftBackedCache.this::serialize), true, Duration.ofSeconds(30)); } catch (Throwable t) { log.warn("Could not evict element from RaftBackedCache; not removing from Raft", t); } } catch (InvalidProtocolBufferException e) { log.warn("Could not deserialize Raft value for key {}", key); } } return CompletableFuture.completedFuture(false); })); } } } // 2. Determine if we've run over our size constraint. If we have, then find the keys that have been idle for // as long as possible, and evict them. Collection<Map.Entry<String, KeyValueStateMachine.ValueWithOptionalOwner>> entrySet = raft.stateMachine.entries(); long sizeInBytes = entrySet.stream().mapToInt(entry -> entry.getValue().value.length).sum(); if (sizeInBytes > maxSizeBytes) { List<Map.Entry<String, KeyValueStateMachine.ValueWithOptionalOwner>> entries = new ArrayList<>(entrySet); // note[gabor]: This is copying from a ConcurrentHashMap entrySet Map<String, Long> cachedLastAccessed = new HashMap<>(); // note[gabor]: See #200. We need to ensure a fixed value of lastAccessed entries.sort(Comparator.comparingLong(entry -> cachedLastAccessed.computeIfAbsent(entry.getKey(), k -> entry.getValue().lastAccessed))); long sizeNeeded = maxSizeBytes - sizeInBytes; for (Map.Entry<String, KeyValueStateMachine.ValueWithOptionalOwner> keyAndvalue : entries) { if (sizeNeeded <= 0) break; sizeNeeded -= keyAndvalue.getValue().value.length; // Save the entry, and remove it String key = keyAndvalue.getKey(); if (key.startsWith(prefix())) { String localKey = key.replace(prefix(), ""); evictionTasksRunning.add(raft.withDistributedLockAsync(key, () -> { Optional<byte[]> valueBytes = raft.getElement(key); if (valueBytes.isPresent()) { if (!Entry.readIsPersisted(valueBytes.get())) { try { Entry<V> entry = Entry.deserialize(localKey, valueBytes.get(), RaftBackedCache.this::deserialize); // 4. Evict the value from Raft - opportunity to save the value somewhere else log.info("Persisting RaftBackedCache element with key {} in preparation for eviction", localKey); persist(localKey, entry.value, false); } catch (InvalidProtocolBufferException e) { log.warn("Could not deserialize Raft value for key {}", key); } } log.info("Evicting RaftBackedCache element with key {}", localKey); // 5. Remove the value from the Raft state machine. return raft.removeElementAsync(key, Duration.ofSeconds(30)); } return CompletableFuture.completedFuture(false); })); } } } } }; this.raft.node.transport.scheduleAtFixedRate(evictionTask, 1000); } /** * Create a Raft backed cache with the default Raft implementation. */ protected RaftBackedCache(Theseus raft, Duration idleDuration, Duration elementLifetime) { this(raft, idleDuration, elementLifetime, DEFAULT_MAX_SIZE_BYTES); } /** * This creates a new CompletableFuture for all the currently outstanding eviction tasks. * * @return a NEW CompletableFuture for all the outstanding eviction tasks. If none outstanding, returns a completed * future. */ public CompletableFuture<Void> allOutstandingEvictionsFuture() { synchronized (evictionTasksRunning) { return CompletableFuture.allOf(evictionTasksRunning.toArray(new CompletableFuture[0])); } } /** * This cleans up the eviction timer. It also */ public void close() { evictionTask.cancel(); } /** * The raft prefix to use on {@link #get(String)} and {@link #put(String, Object, boolean)} to translate from our * local namespace to Raft's global namespace */ protected abstract String prefix(); /** * Serialize an object of our value type into a byte array. We need to be able to do this * so that we can store it in the Raft state machine. * This must be able to be reread with {@link #deserialize(byte[])}. * * @param object The object we are serializing. * * @return A byte[] representation of the object. * * @see #deserialize(byte[]) */ public abstract byte[] serialize(V object); /** * Read an object in our cache, written with {@link #serialize(Object)}, into a value type. * * @param serialized The serialized blob we are reading. * * @return The value corresponding to the protocol buffer. * * @see #serialize(Object) */ public abstract Optional<V> deserialize(byte[] serialized); /** * Get a value from wherever it was evicted to, if we can. * This is the inverse of {@link #persist(String, Object, boolean)}. * * @param key The key of the element we're creating / retrieving. * * @return The value of the element we've created / retrieved. * * @see #persist(String, Object, boolean) */ public abstract Optional<V> restore(String key); /** * Evict an element from our cache. This can either actually throw it away, or save it to a * persistence store. * If you chose the latter, make sure to have {@link #restore(String)} first try to retrieve the * element from this persistence store. * * @param key The key we are evicting. * @param value The value we are evicting. * @param async If true, the save is allowed to be asynchronous. * This is often the case where, e.g., we're saving on a creation when we * should not be blocking the main thread. */ public abstract void persist(String key, V value, boolean async); /** * This iterates through all the elements in the Raft backed cache and evicts them, using only a single Raft commit * to do it. */ public CompletableFuture<Boolean> clearCache() { Set<String> toRemove = new HashSet<>(); for (String key : raft.stateMachine.values.keySet()) { if (key.startsWith(prefix())) { toRemove.add(key); } } return this.raft.removeElementsAsync(toRemove, Duration.ofSeconds(30)); } /** * This registers a listener that will be called whenever the key-value store changes. * * @param changeListener the listener to register * @param owner the owner of the change listener. This is a failsafe to make * sure we remove the listener when the owner dies, but is not required. */ public void addChangeListener(ChangeListener<V> changeListener, @Nullable Object owner) { // 1. Create the Raft listener KeyValueStateMachine.ChangeListener keyValueListener = (key, value, state) -> { if (key.startsWith(prefix())) { key = key.replace(prefix(), ""); Optional<V> parsedValue = Optional.empty(); if (value.isPresent()) { try { parsedValue = Optional.of(Entry.deserialize(key, value.get(), this::deserialize).value); } catch (Throwable t) { log.warn("Could not parse entry in change listener", t); } } changeListener.onChange(key, parsedValue); } }; // 2. Register the listener changeListeners.put(changeListener, keyValueListener); raft.addChangeListener(keyValueListener); // 3. Register the owner if (owner != null) { changeListenerOwner.put(changeListener, new WeakReference<>(owner)); // 4. Clean up GC'd listeners (this is a failsafe) Set<ChangeListener> toRemove = new HashSet<>(); for (Map.Entry<ChangeListener, WeakReference<Object>> entry : changeListenerOwner.entrySet()) { if (entry.getValue().get() == null) { toRemove.add(entry.getKey()); } } for (ChangeListener listener : toRemove) { log.warn("Leaked Raft change listener {} on cache {}", listener, this.toString()); removeChangeListener(listener); } } } /** @see #addChangeListener(ChangeListener, Object) */ public void addChangeListener(ChangeListener<V> changeListener) { addChangeListener(changeListener, null); } /** * This registers a listener that will be called whenever the key-value store changes. * * @param changeListener the listener to register */ public void removeChangeListener(ChangeListener changeListener) { KeyValueStateMachine.ChangeListener keyValueListener = changeListeners.get(changeListener); if (keyValueListener != null) { raft.removeChangeListener(keyValueListener); } else { log.warn("No corresponding listener to remove from the KeyValueStateMachine. This is troubling."); } changeListenerOwner.remove(changeListener); } /** * Perform a computation on the given element. * The result of the mutation is then saved into raft, if there was any change. * Note that we can always return the input element if we do not want to save anything * back to Raft. * If the element does not exist, we will call {@link #restore(String)} to ensure that it * is created. * * @param key The key of the element we're computing on. * @param mutator The function to call on the value for the given key. * This takes 2 arguments: the input item, and a function that can be called to sync intermediate * states. It should return the final state to save. * Note that saving intermediate states is done while this object still holds the lock. * So, other processes can only access the result read-only, * @param createNew An optional method for creating a brand new object of the relevant type - only gets called if * element cannot be retrieved from storage * @param unlocked If true, we are not locking the underlying Raft call. */ public CompletableFuture<Boolean> withElementAsync(String key, BiFunction<V, Consumer<V>, V> mutator, @Nullable Supplier<V> createNew, boolean unlocked) { log.trace("WithElement {}", key); Pointer<Boolean> wasCreated = new Pointer<>(false); // A. The mutator (for Raft) Function<byte[], byte[]> mutatorImpl = originalBytes -> { // A.1. Get the entry Entry<V> entry; try { entry = Entry.deserialize(key, originalBytes, this::deserialize); } catch (InvalidProtocolBufferException e) { log.warn("Could not deserialize value for key=" + prefix() + key); return originalBytes; } // A.2. Mutate the entry V mutatedValue = mutator.apply(entry.value, update -> { // Optionally, we can save intermediate states during our mutation. This implements those intermediate saves try { Entry<V> updatedEntry = new Entry<>(key, false, entry.value); this.raft.setElementAsync(prefix() + key, updatedEntry.serialize(this::serialize), true, Duration.ofSeconds(5)).get(6, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.warn("Could not save intermediate state during withElementAsyc call in RaftBackedCache: ", e); } }); // A.3. Check that we've mutated if (mutatedValue != entry.value) { // If we have, persist the element and set it onSet(mutatedValue); boolean persisted = false; if (wasCreated.dereference().orElse(false)) { persisted = true; persist(key, mutatedValue, false); } return new Entry<>(key, persisted, mutatedValue).serialize(this::serialize); } else { // Otherwise, nothing happens return originalBytes; } }; // B. The creator (for Raft) Supplier<byte[]> creatorImpl = () -> { // B.1. Get the value from stable storage Optional<V> obj = restore(key); if (obj.isPresent()) { // If it exists, return that return new Entry<>(key, true, obj.get()).serialize(this::serialize); } else if (createNew != null) { // Create the value V value = createNew.get(); // Register that we were created wasCreated.set(true); // Return the value return new Entry<>(key, false, value).serialize(this::serialize); } else { // Nothing to return return null; } }; // Perform the operation on Raft if (unlocked) { return this.raft.withElementUnlockedAsync(prefix() + key, mutatorImpl, creatorImpl, true); } else { return this.raft.withElementAsync(prefix() + key, mutatorImpl, creatorImpl, true); } } /** * @see #withElementAsync(String, BiFunction, Supplier, boolean) */ public CompletableFuture<Boolean> withElementAsync(String key, Function<V, V> mutator, @Nullable Supplier<V> createNew, boolean unlocked) { return withElementAsync(key, (v, save) -> mutator.apply(v), createNew, unlocked); } /** * @see #withElementAsync(String, Function, Supplier) */ public CompletableFuture<Boolean> withElementAsync(String key, Function<V, V> mutator, Supplier<V> createNew) { return withElementAsync(key, mutator, createNew, false); } /** * @see #withElementAsync(String, Function, Supplier) */ public CompletableFuture<Boolean> withElementAsync(String key, Function<V, V> mutator) { return withElementAsync(key, mutator, null, false); } /** * @see #withElementAsync(String, BiFunction, Supplier, boolean) */ public CompletableFuture<Boolean> withElementAsync(String key, BiFunction<V, Consumer<V>, V> mutator) { return withElementAsync(key, mutator, null, false); } /** * Get an element from the cache. * * @param key The key of the element to get * * @return The element we are getting, if present. */ public Optional<V> get(String key) { Optional<byte[]> simpleGet = raft.stateMachine.get(prefix() + key, TimerUtils.mockableNow().toEpochMilli()); if (simpleGet.isPresent()) { try { return Optional.of(Entry.deserialize(key, simpleGet.get(), this::deserialize).value); } catch (InvalidProtocolBufferException e) { log.warn("Could not read Proto for Raft item"); return Optional.empty(); } } else { Optional<V> value = restore(key); value.ifPresent(v -> raft.setElementAsync(prefix() + key, new Entry<>(key, false, v).serialize(this::serialize), true, Duration.ofSeconds(5))); return value; } } /** * Get an element from the cache, if it's present in the cache itself. * This will not try to get the element from the persistent store. * * @param key The key of the element to get * * @return The element we are getting, if present. */ public Optional<V> getIfPresent(String key) { return raft.stateMachine.get(prefix() + key, TimerUtils.mockableNow().toEpochMilli()).flatMap(v -> { try { return Optional.of(Entry.deserialize(key, v, this::deserialize).value); } catch (InvalidProtocolBufferException e) { return Optional.empty(); } }); } /** * Set an element in Raft. This is really just an alias for {@link Theseus#setElementAsync(String, byte[], boolean, Duration)} * with permanent set to true and a 5 second timeout. */ public CompletableFuture<Boolean> put(String key, V value, boolean persist) { onSet(value); Entry<V> newEntry = new Entry<>(key, false, value); // Persist the key if we should -- blocks if (persist) { this.persist(key, value, false); } // Set the element in Raft return raft.setElementAsync(prefix() + key, newEntry.serialize(this::serialize), true, Duration.ofSeconds(5)); } /** * Remove an element in Raft. This is really just an alias for {@link Theseus#removeElementAsync(String, Duration)}. */ public CompletableFuture<Boolean> evictWithoutSaving(String key) { return raft.removeElementAsync(prefix() + key, Duration.ofSeconds(5)); } /** {@inheritDoc} */ @Nonnull @Override public Iterator<Map.Entry<String,V>> iterator() { String prefix = prefix(); return raft.getMap().entrySet().stream() .filter(x -> x.getKey().startsWith(prefix)) .map(x -> { try { return (Map.Entry<String,V>)Entry.deserialize(x.getKey(), x.getValue(), this::deserialize); } catch (InvalidProtocolBufferException e) { return null; } }) .filter(Objects::nonNull) .iterator(); } /** * This checks whether a value has been saved since the last time we wrote a change to that value in Raft. * * @param key The key of the element we're getting * @return true if we've saved the element since our last write */ private boolean valuePersistedSinceLastWrite(String key) { return raft.getElement(key).filter(Entry::readIsPersisted).isPresent(); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/RaftFailsafe.java
package ai.eloquent.raft; /** * Failsafes are custom detectors that can make use of deploy-specific information (for example, spying on Kubernetes * config) to cheat on CAP theorem limits about detecting cluster deadlocks. */ public interface RaftFailsafe { /** * This gets called every heartbeat from an EloquentRaftAlgorithm where this failsafe is registered. * * @param algorithm the calling algorithm * @param now the current time */ void heartbeat(RaftAlgorithm algorithm, long now); }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/RaftGrpc.java
package ai.eloquent.raft; import static io.grpc.MethodDescriptor.generateFullMethodName; import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall; import static io.grpc.stub.ClientCalls.asyncClientStreamingCall; import static io.grpc.stub.ClientCalls.asyncServerStreamingCall; import static io.grpc.stub.ClientCalls.asyncUnaryCall; import static io.grpc.stub.ClientCalls.blockingServerStreamingCall; import static io.grpc.stub.ClientCalls.blockingUnaryCall; import static io.grpc.stub.ClientCalls.futureUnaryCall; import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall; import static io.grpc.stub.ServerCalls.asyncClientStreamingCall; import static io.grpc.stub.ServerCalls.asyncServerStreamingCall; import static io.grpc.stub.ServerCalls.asyncUnaryCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall; /** */ @javax.annotation.Generated( value = "by gRPC proto compiler (version 1.9.0)", comments = "Source: EloquentRaft.proto") public final class RaftGrpc { private RaftGrpc() {} public static final String SERVICE_NAME = "ai.eloquent.raft.Raft"; // Static method descriptors that strictly reflect the proto. @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") @java.lang.Deprecated // Use {@link #getRpcMethod()} instead. public static final io.grpc.MethodDescriptor<ai.eloquent.raft.EloquentRaftProto.RaftMessage, ai.eloquent.raft.EloquentRaftProto.RaftMessage> METHOD_RPC = getRpcMethod(); private static volatile io.grpc.MethodDescriptor<ai.eloquent.raft.EloquentRaftProto.RaftMessage, ai.eloquent.raft.EloquentRaftProto.RaftMessage> getRpcMethod; @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static io.grpc.MethodDescriptor<ai.eloquent.raft.EloquentRaftProto.RaftMessage, ai.eloquent.raft.EloquentRaftProto.RaftMessage> getRpcMethod() { io.grpc.MethodDescriptor<ai.eloquent.raft.EloquentRaftProto.RaftMessage, ai.eloquent.raft.EloquentRaftProto.RaftMessage> getRpcMethod; if ((getRpcMethod = RaftGrpc.getRpcMethod) == null) { synchronized (RaftGrpc.class) { if ((getRpcMethod = RaftGrpc.getRpcMethod) == null) { RaftGrpc.getRpcMethod = getRpcMethod = io.grpc.MethodDescriptor.<ai.eloquent.raft.EloquentRaftProto.RaftMessage, ai.eloquent.raft.EloquentRaftProto.RaftMessage>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "ai.eloquent.raft.Raft", "rpc")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( ai.eloquent.raft.EloquentRaftProto.RaftMessage.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( ai.eloquent.raft.EloquentRaftProto.RaftMessage.getDefaultInstance())) .setSchemaDescriptor(new RaftMethodDescriptorSupplier("rpc")) .build(); } } } return getRpcMethod; } /** * Creates a new async stub that supports all call types for the service */ public static RaftStub newStub(io.grpc.Channel channel) { return new RaftStub(channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static RaftBlockingStub newBlockingStub( io.grpc.Channel channel) { return new RaftBlockingStub(channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static RaftFutureStub newFutureStub( io.grpc.Channel channel) { return new RaftFutureStub(channel); } /** */ public static abstract class RaftImplBase implements io.grpc.BindableService { /** */ public void rpc(ai.eloquent.raft.EloquentRaftProto.RaftMessage request, io.grpc.stub.StreamObserver<ai.eloquent.raft.EloquentRaftProto.RaftMessage> responseObserver) { asyncUnimplementedUnaryCall(getRpcMethod(), responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getRpcMethod(), asyncUnaryCall( new MethodHandlers< ai.eloquent.raft.EloquentRaftProto.RaftMessage, ai.eloquent.raft.EloquentRaftProto.RaftMessage>( this, METHODID_RPC))) .build(); } } /** */ public static final class RaftStub extends io.grpc.stub.AbstractStub<RaftStub> { private RaftStub(io.grpc.Channel channel) { super(channel); } private RaftStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected RaftStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new RaftStub(channel, callOptions); } /** */ public void rpc(ai.eloquent.raft.EloquentRaftProto.RaftMessage request, io.grpc.stub.StreamObserver<ai.eloquent.raft.EloquentRaftProto.RaftMessage> responseObserver) { asyncUnaryCall( getChannel().newCall(getRpcMethod(), getCallOptions()), request, responseObserver); } } /** */ public static final class RaftBlockingStub extends io.grpc.stub.AbstractStub<RaftBlockingStub> { private RaftBlockingStub(io.grpc.Channel channel) { super(channel); } private RaftBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected RaftBlockingStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new RaftBlockingStub(channel, callOptions); } /** */ public ai.eloquent.raft.EloquentRaftProto.RaftMessage rpc(ai.eloquent.raft.EloquentRaftProto.RaftMessage request) { return blockingUnaryCall( getChannel(), getRpcMethod(), getCallOptions(), request); } } /** */ public static final class RaftFutureStub extends io.grpc.stub.AbstractStub<RaftFutureStub> { private RaftFutureStub(io.grpc.Channel channel) { super(channel); } private RaftFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected RaftFutureStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new RaftFutureStub(channel, callOptions); } /** */ public com.google.common.util.concurrent.ListenableFuture<ai.eloquent.raft.EloquentRaftProto.RaftMessage> rpc( ai.eloquent.raft.EloquentRaftProto.RaftMessage request) { return futureUnaryCall( getChannel().newCall(getRpcMethod(), getCallOptions()), request); } } private static final int METHODID_RPC = 0; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final RaftImplBase serviceImpl; private final int methodId; MethodHandlers(RaftImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_RPC: serviceImpl.rpc((ai.eloquent.raft.EloquentRaftProto.RaftMessage) request, (io.grpc.stub.StreamObserver<ai.eloquent.raft.EloquentRaftProto.RaftMessage>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private static abstract class RaftBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { RaftBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return ai.eloquent.raft.EloquentRaftProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("Raft"); } } private static final class RaftFileDescriptorSupplier extends RaftBaseDescriptorSupplier { RaftFileDescriptorSupplier() {} } private static final class RaftMethodDescriptorSupplier extends RaftBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; RaftMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (RaftGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new RaftFileDescriptorSupplier()) .addMethod(getRpcMethod()) .build(); } } } return result; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/RaftLifecycle.java
package ai.eloquent.raft; import ai.eloquent.util.*; import ai.eloquent.web.TrackedExecutorService; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; public class RaftLifecycle { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(RaftLifecycle.class); public static RaftLifecycle global = RaftLifecycle.newBuilder().build(); /** * A global timer that we can use. */ public Lazy<SafeTimer> timer; /** The set of managed thread pools */ protected final Map<String, ExecutorService> managedThreadPools = new HashMap<>(); /** The set of managed thread pools, which run core system-level things (e.g., Rabbit or the DB connections). */ protected final Map<String, ExecutorService> coreThreadPools = new HashMap<>(); /** This is the Theseus that's tied to this RaftLifecycle - if any. We use this knowledge on shutdown. */ protected Optional<EloquentRaftNode> registeredRaft = Optional.empty(); public RaftLifecycle(Lazy<SafeTimer> timer) { this.timer = timer; } /** * A builder for a lifecycle. */ public static class Builder { private boolean mockTimer = false; public Builder mockTime() { this.mockTimer = true; return this; } public RaftLifecycle build() { Lazy<SafeTimer> timer; if (this.mockTimer) { timer = Lazy.of(SafeTimerMock::new); } else { timer = Lazy.of(SafeTimerReal::new); } return new RaftLifecycle(timer); } } /** * Create a new lifecycle builder. */ public static Builder newBuilder() { return new Builder(); } /** * This registers Raft on this RaftLifecycle, so that the RaftLifecycle can shut it down when it's ready. */ public void registerRaft(EloquentRaftNode raft) { this.registeredRaft = Optional.of(raft); } /** * This creates a helpful prefix for watching the log messages of RaftLifecycle when we have multiple RaftLifecycle objects in * the same test. */ private String logServerNamePrefix() { return registeredRaft.map(eloquentRaftNode -> eloquentRaftNode.algorithm.serverName() + " - ").orElse(""); } /** * Create a thread pool that closes itself on program shutdown. * * @param numThreads The number of threads to allocate in the pool * @param threadPrefix When naming threads, use this prefix to identify threads in this pool vs. other pools. * @param core If true, this is a core system thread pool. Core thread pools are shut down after Rabbit and the database close, * whereas non-core thread pools close with Rabbit and the database still open. * @param priority The priority of the threads scheduled on this pool. * * @return The thread pool created. */ public ExecutorService managedThreadPool(int numThreads, String threadPrefix, boolean core, int priority) { if ((core && !coreThreadPools.containsKey(threadPrefix)) || (!core && !managedThreadPools.containsKey(threadPrefix))) { ExecutorService service; if (numThreads == 1) { service = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder() .setNameFormat(threadPrefix + "-%d") .setDaemon(true) .setUncaughtExceptionHandler((t, e) -> log.warn("Uncaught exception on thread " + t.getName(), e)) .setPriority(priority) .build()); } else { service = Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setNameFormat(threadPrefix + "-%d").setDaemon(true).build()); } if (this == RaftLifecycle.global) { service = new TrackedExecutorService(threadPrefix, service); } if (core) { coreThreadPools.put(threadPrefix, service); } else { managedThreadPools.put(threadPrefix, service); } } else { log.warn(logServerNamePrefix() + "Getting a thread pool that already exists for \"" + threadPrefix + "\", but asking for a pool with a " + "fixed size = " + numThreads + ". This will likely lead to trouble as multiple people each think they have " + "exclusive access to " + numThreads + " threads, when in fact they do not", new IllegalStateException()); } if (core) return coreThreadPools.get(threadPrefix); else return managedThreadPools.get(threadPrefix); } /** * @see #managedThreadPool(int, String, boolean, int) */ public ExecutorService managedThreadPool(int numThreads, String threadPrefix, boolean core) { return managedThreadPool(numThreads, threadPrefix, core, Thread.NORM_PRIORITY); } /** * @see #managedThreadPool(int, String, boolean, int) */ public ExecutorService managedThreadPool(int numThreads, String threadPrefix, int priority) { return managedThreadPool(numThreads, threadPrefix, false, priority); } /** * @see #managedThreadPool(int, String, boolean) */ public ExecutorService managedThreadPool(int numThreads, String threadPrefix) { return managedThreadPool(numThreads, threadPrefix, false); } /** * Create a managed cached thread pool. * * @param threadPrefix The prefix to apply to all the threads in the pool * @param core If true, this is a core system thread pool. Core thread pools are shut down after Rabbit and the database close, * whereas non-core thread pools close with Rabbit and the database still open. * @param priority The priority of the threads scheduled on this pool. * * @return The thread pool. */ public ExecutorService managedThreadPool(String threadPrefix, boolean core, int priority) { if ((core && !coreThreadPools.containsKey(threadPrefix)) || (!core && !managedThreadPools.containsKey(threadPrefix))) { ExecutorService service = Executors.newCachedThreadPool( new ThreadFactoryBuilder() .setNameFormat(threadPrefix + "-%d") .setDaemon(true) .setUncaughtExceptionHandler((t, e) -> log.warn("Uncaught exception on thread " + t.getName(), e)) .setPriority(priority) .build()); if (this == RaftLifecycle.global) { service = new TrackedExecutorService(threadPrefix, service); } if (core) { coreThreadPools.put(threadPrefix, service); } else { managedThreadPools.put(threadPrefix, service); } } if (core) { return coreThreadPools.get(threadPrefix); } else { return managedThreadPools.get(threadPrefix); } } /** * @see #managedThreadPool(String, boolean, int) */ public ExecutorService managedThreadPool(String threadPrefix, boolean core) { return managedThreadPool(threadPrefix, core, Thread.NORM_PRIORITY); } /** * Create a managed cached thread pool. * * @param threadPrefix The prefix to apply to all the threads in the pool * * @return The thread pool. */ public ExecutorService managedThreadPool(String threadPrefix) { return managedThreadPool(threadPrefix, false, Thread.NORM_PRIORITY); } /** * Create a managed cached thread pool with a given priority. * * @param threadPrefix The prefix to apply to all the threads in the pool * @param priority The priority of the threads scheduled on this pool. * * @return The thread pool. */ public ExecutorService managedThreadPool(String threadPrefix, int priority) { return managedThreadPool(threadPrefix, false, priority); } // Stuff to shut down elegantly /** The set of shutdown hooks we should run on shutdown, once we are no longer receiving traffic */ protected final IdentityHashSet<Runnable> shutdownHooks = new IdentityHashSet<>(); /** The indicator for whether our web server is accepting new requests. */ public final AtomicBoolean IS_READY = new AtomicBoolean(false); /** * This indicator gets set when we are shutting down, and should not allow new requests to proceed. * This is subtly different from {@link RaftLifecycle#IS_READY}, in that Kubernetes can send new requests * between when {@link RaftLifecycle#IS_READY} is marked false, and when its timeout on readiness checks * expires. * In contrast, this variable is only set once Kubernetes should no longer be sending us new requests. * Any new requests that are sent should be considered to be an error. */ public final AtomicBoolean IS_SHUTTING_DOWN = new AtomicBoolean(false); /** * This indicates when we have started a shutdown. * As distinct from {@link #IS_READY} (indicating the Kubernetes readiness state), * and {@link #IS_SHUTTING_DOWN} (indicating that readiness is down and we're */ public final AtomicBoolean SHUTDOWN_BEGIN = new AtomicBoolean(false); /** * This indicates when we have closed the core thread pools, one of the last steps right before shutdown. This is here * so that mocks that simulate multiple EloquentLifecycle objects on the same VM can stop performing actions that would have * executed on a core thread pool. */ public final AtomicBoolean CORE_THREAD_POOLS_CLOSED = new AtomicBoolean(false); /** The interval in which liveness and readiness checks are sent to our server. This must match deployment.yaml. */ public static final int STATUS_PERIOD_SEC = 2; /** The number of readiness checks we have to fail for us to be considered dead by Kuberneters. This must match deployment.yaml. */ public static final int STATUS_FAILURE_THRESHOLD = 3; /** The timeout on the ready endpoint. This should match deployment.yaml. */ public static final int STATUS_TIMEOUT_SEC = 5; /** * A lock we can take to prevent the system from shutting down. * This can be used to, e.g., create critical sections of code that cannot be * interrupted by the system shutting down. */ protected final Set<ReentrantLock> criticalSections = new IdentityHashSet<>(); /** * If false, throw an exception rather than entering the critical section. * This is the case when we are already in the process of shutting down and we attempt * to enter a new critical section. */ protected boolean allowCriticalSections = true; static { // Set up the shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(() -> { // if we're on a CI server (where shutdown doesn't matter) if (System.getenv("CI") != null) { return; } log.info(global.logServerNamePrefix()+"-----------------BEGIN SHUTDOWN " + SystemUtils.HOST + "--------------------"); // 1-11. Run shutdown global.shutdown(false); // N+1. Shutdown logging log.info(global.logServerNamePrefix()+"-----------------END SHUTDOWN " + SystemUtils.HOST + "--------------------"); Uninterruptably.sleep(1000); // sleep a while to give everyone a chance to flush if they haven't already log.info(global.logServerNamePrefix()+"Done with shutdown"); log.info(global.logServerNamePrefix()+"-----------------TERMINATION " + SystemUtils.HOST + "--------------------"); })); } /** * This is called from the shutdown hooks, but also can be called from within tests to simulate a shutdown for a * single EloquentLifecycle * * @param allowClusterDeath If true, allow the Raft cluster to lose state and completely shut down. * Otherwise, we wait for another live node to show up before shutting * down (the default). */ @SuppressWarnings("Duplicates") public void shutdown(boolean allowClusterDeath) { if (SHUTDOWN_BEGIN.getAndSet(true)) { // If we're already shutting down somewhere else, prevent a duplicate shutdown log.warn(logServerNamePrefix()+"Detected an attempt to double-shutdown. Ignoring."); return; } // 1. Run a GC (concurrently) Thread gcThread = new Thread( () -> { log.info(global.logServerNamePrefix()+"Memory (pre-gc): free=" + Runtime.getRuntime().freeMemory() / (1024 * 1024) + "MB total=" + Runtime.getRuntime().totalMemory() / (1024 * 1024) + "MB max=" + Runtime.getRuntime().maxMemory() / (1024 * 1024) + "MB"); Runtime.getRuntime().gc(); // Run an explicit GC log.info(global.logServerNamePrefix()+"Memory (post-gc): free=" + Runtime.getRuntime().freeMemory() / (1024 * 1024) + "MB total=" + Runtime.getRuntime().totalMemory() / (1024 * 1024) + "MB max=" + Runtime.getRuntime().maxMemory() / (1024 * 1024) + "MB"); }); gcThread.setDaemon(true); gcThread.setName("shutdown-gc"); gcThread.start(); // 2. Bring readiness down and wait if (IS_READY.getAndSet(false)) { long msToWait = ((RaftLifecycle.STATUS_PERIOD_SEC + RaftLifecycle.STATUS_TIMEOUT_SEC) * 1000 * STATUS_FAILURE_THRESHOLD) + 2000; // +2s for good measure log.info(logServerNamePrefix()+"Waiting " + TimerUtils.formatTimeDifference(msToWait) + " before shutting down to let Kubernetes detect we're not READY..."); Uninterruptably.sleep(msToWait); } // -- After this point, Kubernetes should not be sending us any more requests. We are just shutting down gracefully. // -- We also don't necessarily have an accessible IP address anymore; other boxes (and the public) may not see us. IS_SHUTTING_DOWN.set(true); // 3. Disallow requests + kill Jetty // 3.1. Disallow requests synchronized (criticalSections) { allowCriticalSections = false; } // 4. Run shutdown hooks log.info(logServerNamePrefix()+"Running shutdown hooks (1 minute timeout on each)"); Set<Runnable> hooks; synchronized (shutdownHooks) { hooks = new HashSet<>(shutdownHooks); } hooks.stream().map(task -> { log.info(logServerNamePrefix()+"Starting shutdown task {}", task.getClass()); Thread t = new Thread(task); t.setName("shutdown-hook"); t.start(); return Pair.makePair(t, task.getClass()); }).collect(Collectors.toList()).forEach(pair -> { try { pair.first.join(Duration.ofMinutes(1).toMillis()); log.info(logServerNamePrefix()+"Joined shutdown task {}", pair.second); } catch (InterruptedException e) { log.warn(logServerNamePrefix()+"Shutdown hook got interrupted before it could finish!"); } }); // 5. Await critical sections log.info(logServerNamePrefix()+"Waiting on critical sections to finish (max 1 minute)..."); Set<ReentrantLock> criticalSectionsToAwait; synchronized (criticalSections) { allowCriticalSections = false; // redundant with call at top of shutdown hook criticalSectionsToAwait = new IdentityHashSet<>(criticalSections); } criticalSectionsToAwait.forEach(x -> { try { x.tryLock(Duration.ofMinutes(1).toMillis(), TimeUnit.MILLISECONDS); // allow 1 minute for each critical section to finish } catch (InterruptedException ignored) {} }); // 6. Run a final GC log.info(logServerNamePrefix()+"Finalizing as much as we can (connections are still alive)"); try { gcThread.join(30000); } catch (InterruptedException e) { log.warn("shutdown GC thread interrupted before completion"); } System.runFinalization(); // 7. Shutdown our RAFT cluster, if we have one, and block until shutdown is complete this.registeredRaft.ifPresent(raft -> { log.info(logServerNamePrefix() + "Shutting down raft (blocking={})...", !allowClusterDeath); raft.close(allowClusterDeath); // wait for someone else to come online to carry on the state (if we have a raft at all) log.info(logServerNamePrefix() + "Raft shut down"); }); // 8. Cancel the timers log.info(logServerNamePrefix()+"Cancelling timers"); Optional.ofNullable(timer.getIfDefined()).ifPresent(SafeTimer::cancel); log.info(logServerNamePrefix()+"Timers cancelled"); // 9. Shutdown all the managed thread pools, and wait a max of 1 min for everything to shut down log.info(logServerNamePrefix()+"Stopping non-essential thread pools"); stopPool(managedThreadPools.values()); log.info(logServerNamePrefix()+"All non-essential threads should be stopped"); // 10. Shutdown core thread pools log.info(logServerNamePrefix()+"Stopping core thread pools"); stopPool(coreThreadPools.values()); log.info(logServerNamePrefix()+"All core thread pools should be stopped"); CORE_THREAD_POOLS_CLOSED.set(true); // 11. Finalize everything again, to clean up connections log.info(logServerNamePrefix()+"Finalizing as much as we can (connections are dead)"); System.runFinalization(); } /** * Shut down a thread pool collection. * This is a common method for stopping {@link #managedThreadPools} and * {@link #coreThreadPools}. * * @param pool The thread pool collection to stop. */ protected void stopPool(Collection<ExecutorService> pool) { pool.stream().map((service) -> { service.shutdown(); Thread awaitTermination = new Thread(() -> { try { long start = System.currentTimeMillis(); service.awaitTermination(1, TimeUnit.MINUTES); if (System.currentTimeMillis() - start > 1000 * 55) { log.warn(logServerNamePrefix()+"Service took >55s to shut down: {}", service); } } catch (InterruptedException ignored) {} }); awaitTermination.setDaemon(true); awaitTermination.setName("waiting for " + service + " to terminate"); awaitTermination.start(); return awaitTermination; }).forEach(thread -> { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); log.info(logServerNamePrefix()+"pools stopped"); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/RaftLog.java
package ai.eloquent.raft; import ai.eloquent.monitoring.Prometheus; import ai.eloquent.util.FunctionalUtils; import ai.eloquent.util.TimerUtils; import com.sun.management.GcInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; /** * There turns out to be an annoying amount of book-keeping around the logging abstraction in Raft, since it can be * compacted, truncated, rewritten, committed, and queried in all sorts of strange ways. That made it an excellent * candidate to become a class and get tested in isolation. */ @SuppressWarnings("OptionalIsPresent") public class RaftLog { /** * An SLF4J Logger for this class. */ @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(RaftLog.class); /** * <li>0: trace</li> * <li>1: debug</li> * <li>2: info</li> (Default) * <li>3: warn</li> * <li>4: error</li> * <li>99: off</li> */ private static int minLogLevel = 2; /** * Explicitly set the log level. These are: * * <ul> * <li>0: trace</li> * <li>1: debug</li> * <li>2: info</li> * <li>3: warn</li> * <li>4: error</li> * </ul> */ public static void setLevel(int level) { minLogLevel = level; } /** * Explicitly set the log level. These are: * * <ul> * <li>trace</li> * <li>debug</li> * <li>info</li> * <li>warn</li> * <li>error</li> * <li>off</li> * </ul> * * On an invalid level, we default to 'info' */ public static void setLevel(String level) { switch (level.toLowerCase()) { case "trace": case "0": minLogLevel = 0; break; case "debug": case "1": minLogLevel = 1; break; case "info": case "2": minLogLevel = 2; break; case "warn": case "3": minLogLevel = 3; break; case "error": case "4": minLogLevel = 4; break; case "off": case "5": minLogLevel = 99; break; default: minLogLevel = 2; } } /** * Get the current log level. */ public static int level() { return minLogLevel; } /** * The number of log entries to keep in the log before compacting into a snapshot. */ public static final int COMPACTION_LIMIT = 1024; /** * A pool for completing commit futures. */ private final ExecutorService pool; /** * This holds a listener for when a commit has reached a certain index. */ private static class CommitFuture { public final long index; public final long term; public final Consumer<Boolean> complete; public CommitFuture(long index, long term, Consumer<Boolean> complete) { this.index = index; this.term = term; this.complete = complete; } } /** * This is used in truncating the logs when they grow too long. */ public static class Snapshot { byte[] serializedStateMachine; // the snapshot replaces all entries up through and including this index long lastIndex; // term of lastIndex long lastTerm; // latest cluster configuration as of lastIndex Set<String> lastClusterMembership; public Snapshot(byte[] serializedStateMachine, long lastIndex, long lastTerm, Collection<String> lastClusterMembership) { this.serializedStateMachine = serializedStateMachine; this.lastIndex = lastIndex; this.lastTerm = lastTerm; this.lastClusterMembership = FunctionalUtils.immutable(new HashSet<>(lastClusterMembership)); } } /** * The index (inclusive) up to which the log has been committed. */ long commitIndex; /** * CORE: This is a deque, so that we can support compaction as the log grows long. The first entry is the oldest * entry, the last entry is the newest entry. It is compacted by clipping entries from the beginning. It grows by * appending to the end. */ final Deque<EloquentRaftProto.LogEntry> logEntries = new ArrayDeque<>(COMPACTION_LIMIT); /** * CORE: This is the state machine reference that the logs refer to. */ public final RaftStateMachine stateMachine; /** * CORE: This is used by leaders to know when a commit has been replicated and it's safe to respond to a caller */ final List<CommitFuture> commitFutures = new ArrayList<>(); /** * LOG COMPACTION: This is used to backstop the log when we compact committed entries. */ public Optional<Snapshot> snapshot = Optional.empty(); /** * MEMBERSHIP CHANGES: This is used to keep track of the current membership of the cluster. */ final Set<String> latestQuorumMembers = new HashSet<>(); /** * LOG COMPACTION + MEMBERSHIP CHANGES: This is used for log compaction, so we can track membership at the time of a * snapshot of the state. */ public final Set<String> committedQuorumMembers = new HashSet<>(); /** * An immutable set denoting the initial configuration, in the corner case that we've completely * deleted a log and need to revert to this state. */ private Set<String> initialQuorumMembers; /** * Metrics on Raft timing. */ private static Object summaryTiming = Prometheus.summaryBuild("raft_log", "Timing on the Raft log methods"); /** Create a log from a state machine and initial configuration. */ public RaftLog(RaftStateMachine stateMachine, Collection<String> initialConfiguration, ExecutorService pool) { this.stateMachine = stateMachine; this.commitIndex = 0; this.initialQuorumMembers = FunctionalUtils.immutable(new HashSet<>(initialConfiguration)); this.latestQuorumMembers.addAll(initialConfiguration); this.committedQuorumMembers.addAll(initialConfiguration); this.pool = pool; } /** * Assert that the given operation was fast enough that we're likely not waiting on a lock somewhere. * * @param description The action we're performing. * @param summaryStartTime The time the action started. * * @return Always true, so we can be put into asserts */ @SuppressWarnings("Duplicates") private boolean fast(String description, Object summaryStartTime) { long duration = (long) (Prometheus.observeDuration(summaryStartTime) * 1000); if (duration > 5) { long lastGcTime = -1L; try { for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) { com.sun.management.GarbageCollectorMXBean sunGcBean = (com.sun.management.GarbageCollectorMXBean) gcBean; GcInfo lastGcInfo = sunGcBean.getLastGcInfo(); if (lastGcInfo != null) { lastGcTime = lastGcInfo.getStartTime(); } } } catch (Throwable t) { log.warn("Could not get GC info -- are you running on a non-Sun JVM?"); } boolean interruptedByGC = false; if (lastGcTime > System.currentTimeMillis() - duration && lastGcTime < System.currentTimeMillis()) { interruptedByGC = true; } log.warn("{} took {}; interrupted_by_gc={}", description, TimerUtils.formatTimeDifference(duration), interruptedByGC); } return true; } /** * Create a medium-deep copy of this log. * The state machine is not copied, and the futures are not copied, but the cluster configuration is. */ public RaftLog copy() { Object timerStart = Prometheus.startTimer(summaryTiming); try { assertConsistency(); RaftLog copy = new RaftLog(this.stateMachine, Collections.emptyList(), this.pool); copy.latestQuorumMembers.addAll(this.latestQuorumMembers); copy.committedQuorumMembers.addAll(this.committedQuorumMembers); copy.logEntries.addAll(this.logEntries); copy.commitFutures.addAll(this.commitFutures); copy.commitIndex = this.commitIndex; copy.snapshot = this.snapshot; assert copy.equals(this) : "Copy did not copy the log state entirely"; return copy; } finally { assert fast("copy", timerStart); } } /** * This is an <b>extremely</b> unsafe method that clobbers the current configuration with a new one, without * consulting the log. This is only suitable for bootstrapping. * * @param initialConfiguration The configuration to force into the system -- this also overwrites the log's * native {@link #initialQuorumMembers}. */ void unsafeBootstrapQuorum(Collection<String> initialConfiguration) { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { assert getQuorumMembers().isEmpty() : "Cannot bootstrap from an existing quorum"; this.initialQuorumMembers = FunctionalUtils.immutable(new HashSet<>(initialConfiguration)); this.latestQuorumMembers.clear(); this.latestQuorumMembers.addAll(initialConfiguration); this.snapshot = Optional.empty(); this.logEntries.clear(); this.commitIndex = 0; } finally { assert fast("unsafeBootstrapQuorum", timerStart); assertConsistency(); } } /** * This gets called when preparing an AppendEntriesRPC, in order to send other members the * * This returns the commit index that we've applied up to. */ public long getCommitIndex() { assertConsistency(); return commitIndex; } /** * This gets called when preparing to call an RequestVoteRPC, in order to prevent other members from voting for an * out-of-date log. * * This returns index of the last log entry, regardless of whether it's been committed or not */ public long getLastEntryIndex() { // Note: don't run consistency on this method if (logEntries.size() > 0) { return logEntries.getLast().getIndex(); } else if (snapshot.isPresent()) { // the index of the entry that was actually the last one to be compacted is actually the prevLogIndex + 1 of the // snapshot return snapshot.get().lastIndex; } else { // We say the index of the entry before any entries are added is 0 return 0L; } } /** * This gets called when preparing to call an RequestVoteRPC, in order to prevent other members from voting for an * out-of-date log. * * This returns index of the last log entry, regardless of whether it's been committed or not */ public long getLastEntryTerm() { assertConsistency(); try { if (logEntries.size() > 0) { return logEntries.getLast().getTerm(); } else if (snapshot.isPresent()) { // the index of the entry that was actually the last one to be compacted is actually the prevLogIndex + 1 of the // snapshot return snapshot.get().lastTerm; } else { // We say the term of the entry before any entries are added is 0 return 0L; } } finally { assertConsistency(); } } /** * This returns the most up-to-date view of the cluster membership that we have. */ public Set<String> getQuorumMembers() { assertConsistency(); return this.latestQuorumMembers; } /** * @return all entries that haven't been snapshotted yet. */ public List<EloquentRaftProto.LogEntry> getAllUncompressedEntries() { assertConsistency(); return new ArrayList<>(this.logEntries); } /** * This gets called when preparing to call an AppendEntriesRPC, in order to send other members of the cluster the * current view of the log. * * @param startIndex the index (inclusive) to get the logs from * @return all the log entries starting at a given log index. If we've already compacted startIndex, then we * return empty. */ public Optional<List<EloquentRaftProto.LogEntry>> getEntriesSinceInclusive(long startIndex) { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { // Requesting an update in the future is just requesting a heartbeat if (startIndex > getLastEntryIndex()) return Optional.of(new ArrayList<>()); // This would indicate that we've already compacted this part of the logs if (!getEntryAtIndex(startIndex).isPresent()) return Optional.empty(); // Get the entries List<EloquentRaftProto.LogEntry> entries = new ArrayList<>(); for (long i = startIndex; i <= getLastEntryIndex(); i++) { Optional<EloquentRaftProto.LogEntry> optionalLogEntry = getEntryAtIndex(i); assert (optionalLogEntry.isPresent()); entries.add(optionalLogEntry.get()); } return Optional.of(entries); } finally { assertConsistency(); assert fast("getEntriesSinceInclusive", timerStart); } } /** * This gets called when preparing to call an AppendEntriesRPC, in order to send other members of the cluster the * current view of the log. * * @param index the index to find the term of (if possible) * @return the term, if this entry is in our logs */ public Optional<Long> getPreviousEntryTerm(long index) { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { // Requesting an update in the future if (index > getLastEntryIndex()) { return Optional.empty(); } // If this is referring to the term of the lastIndex in the snapshot, return that if (snapshot.isPresent() && snapshot.get().lastIndex == index) { return Optional.of(snapshot.get().lastTerm); } // If the entry is just in the logs, then return that Optional<EloquentRaftProto.LogEntry> entry = getEntryAtIndex(index); if (entry.isPresent()) { return Optional.of(entry.get().getTerm()); } // We always initialize to the 0 term if (index == 0) { return Optional.of(0L); } // Otherwise this is out of bounds return Optional.empty(); } finally { assertConsistency(); assert fast("getPreviousEntryTerm", timerStart); } } /** * This should only be called by leaders while appending to their log! * * Raft only allows one membership change to be uncommitted at a time. If we already have a membership change in the * log, and it's uncommitted, this returns false. Otherwise, this returns true. * * @return if it's safe to add an uncommitted membership change to the log. */ public boolean getSafeToChangeMembership() { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { // If any uncommitted entry is of type CONFIGURATION, return false for (long i = commitIndex + 1; i <= getLastEntryIndex(); i++) { Optional<EloquentRaftProto.LogEntry> entry = getEntryAtIndex(i); assert (entry.isPresent()); // We can't have compacted entries that are after our commit index if (entry.get().getType() == EloquentRaftProto.LogEntryType.CONFIGURATION) return false; } // Otherwise, return true return true; } finally { assertConsistency(); assert fast("getSafeToChangeMembership", timerStart); } } /** * Get the location of the most recent log entry. * Note that this does <b>NOT</b> search into snapshots -- this just takes entries in * the actual log. * * @return The index of the most recent log entry. */ public Optional<RaftLogEntryLocation> lastConfigurationEntryLocation() { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { Iterator<EloquentRaftProto.LogEntry> iter = this.logEntries.descendingIterator(); while (iter.hasNext()) { EloquentRaftProto.LogEntry entry = iter.next(); if (!entry.getConfigurationList().isEmpty()) { return Optional.of(new RaftLogEntryLocation(entry.getIndex(), entry.getTerm())); } } return Optional.empty(); } finally { assertConsistency(); assert fast("lastConfigurationEntryLocation", timerStart); } } /** * This returns a CompletableFuture of a boolean indicating whether or not this entry was successfully committed to * the logs. This is used to allow a leader to have a callback once a given transition has either committed to the * logs, or failed to commit to the logs. We know when we've had a failure when a commit has a different term number * than expected. That indicates it was overwritten. * * @param index the index we're interested in hearing about * @param term the term we expect the index to be in * @param isInternal if true, this is an internal future that should complete on the master Raft thread. * Otherwise, we complete it on the worker pool. * * @return a CompletableFuture */ CompletableFuture<Boolean> createCommitFuture(long index, long term, boolean isInternal) { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { CompletableFuture<Boolean> listener = new CompletableFuture<>(); // 1. If this is a future for an event that has already happened, then complete it now if (index <= getCommitIndex()) { // 1.1. Check if the commit is in the snapshot boolean success = snapshot.map(snap -> index < snap.lastIndex && term <= snap.lastTerm).orElse(false); // 1.2. Otherwise, check the commit in the current log if (!success) { Optional<Long> pastTerm = getPreviousEntryTerm(index); success = (pastTerm.isPresent() && pastTerm.get() == term); if (!success) { log.trace("Failing commit future (bad term; actual={} != expected={})", pastTerm.isPresent() ? pastTerm.get() : "<unk>", term); } } // 1.3. Complete the future listener.complete(success); } else { // If this hasn't happened yet, then add this to a list if (isInternal) { commitFutures.add(new CommitFuture(index, term, listener::complete)); } else { commitFutures.add(new CommitFuture(index, term, success -> this.pool.submit(() -> listener.complete(success)))); } } return listener; } finally { assertConsistency(); assert fast("createCommitFuture", timerStart); } } /** * @see #createCommitFuture(long, long, boolean) */ public CompletableFuture<Boolean> createCommitFuture(long index, long term) { return createCommitFuture(index, term, false); } /** * @see #createCommitFuture(long, long) */ public CompletableFuture<Boolean> createCommitFuture(RaftLogEntryLocation location) { return createCommitFuture(location.index, location.term); } /** * If leaderCommit &gt; commitIndex, set commitIndex = min(leaderCommit, index of last new entry) * * @param leaderCommit the commit from the leader */ public void setCommitIndex(long leaderCommit, long now) { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { if (leaderCommit > commitIndex) { long lastIndex = snapshot.map(s -> s.lastIndex).orElse(0L); if (logEntries.size() > 0) lastIndex = Math.max(logEntries.peekLast().getIndex(), lastIndex); long newCommitIndex = Math.min(leaderCommit, lastIndex); assert (newCommitIndex > commitIndex); // Commit the new entry transitions to the state machine for (EloquentRaftProto.LogEntry entry : this.logEntries) { if (entry.getIndex() > commitIndex && entry.getIndex() <= newCommitIndex) { // if it's a new entry if (entry.getType() == EloquentRaftProto.LogEntryType.TRANSITION) { stateMachine.applyTransition( entry.getTransition().isEmpty() ? Optional.empty() : Optional.of(entry.getTransition().toByteArray()), "".equals(entry.getNewHospiceMember()) ? Optional.empty() : Optional.of(entry.getNewHospiceMember()), now, pool); } else if (entry.getType() == EloquentRaftProto.LogEntryType.CONFIGURATION) { committedQuorumMembers.clear(); committedQuorumMembers.addAll(entry.getConfigurationList()); } else { throw new IllegalStateException("Unrecognized entry type. This likely means we're very very out of date, and should now crash."); } } } // Update the commit index commitIndex = newCommitIndex; assertConsistency(); // Complete any CommitFutures that are waiting for this commit for (CommitFuture commitFuture : new ArrayList<>(commitFutures)) { // (check for success) if (commitIndex >= commitFuture.index) { Optional<Long> termAtCommit = getPreviousEntryTerm(commitFuture.index); boolean success = termAtCommit.map(term -> term == commitFuture.term).orElse(false); if (!success) { if (termAtCommit.isPresent()) { log.trace("Failing commit future (bad term; actual={} != expected={})", termAtCommit.get(), commitFuture.term); } else { log.trace("Failing commit future (bad term; already compacted entry in snapshot)"); } } // (register the future) commitFuture.complete.accept(success); commitFutures.remove(commitFuture); } } } } finally { assertConsistency(); assert fast("setCommitIndex", timerStart); } } /** * This gets called from handleAppendEntriesRPC() in EloquentRaftMember. It handles verifying that an append command * is sound, by checking prevLogIndex and prevLogTerm, and then applying it. * * 1. Reply false if log doesn't contain an entry at prevLogIndex whose term matches prevLogTerm * 2. If an existing entry conflicts with a new one (same index but different terms), delete the existing entry and all * that follow it. * 3. Append any new entries not already in the log * * @param prevLogIndex the log index for the entry immediately preceding the entries to be appended * @param prevLogTerm the log term for the entry immediately preceding the entries to be appended * @param entries the entries to be appended * * @return true if the append command is in the log. */ @SuppressWarnings("ConstantConditions") public boolean appendEntries(long prevLogIndex, long prevLogTerm, List<EloquentRaftProto.LogEntry> entries) { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { // 1. Reply false if log doesn't contain an entry at prevLogIndex whose term matches prevLogTerm Optional<EloquentRaftProto.LogEntry> prevEntry = getEntryAtIndex(prevLogIndex); boolean allowEntry = false; if (prevLogIndex == 0) { allowEntry = true; // Always allow the first entry } else if (prevEntry.isPresent() && prevEntry.get().getTerm() == prevLogTerm) { allowEntry = true; // Allow if there's a matching previous entry } else if (snapshot.isPresent() && snapshot.get().lastTerm == prevLogTerm && snapshot.get().lastIndex == prevLogIndex) { allowEntry = true; // Allow if the snapshot matches the previous entry } assert (entries.stream().noneMatch(entry -> this.getEntryAtIndex(entry.getIndex()).map(savedEntry -> savedEntry.getTerm() > entry.getTerm()).orElse(false))) : "We should never overwrite an entry with a lower term"; if (!allowEntry) { log.trace("Rejecting log transition: prevLogIndex={} prevEntry.getTerm()={} prevLogTerm={} commitIndex={}", prevLogIndex, prevEntry.map(EloquentRaftProto.LogEntry::getTerm).orElse(-1L), prevLogTerm, commitIndex); return false; } // Short circuit for if this is just a heartbeat if (entries.isEmpty()) { // (but: make sure we're not deleting anything) if (this.logEntries.isEmpty()) { // the log is empty and we're not adding anything return true; } if (prevEntry.isPresent() && prevEntry.get().getIndex() == prevLogIndex && prevEntry.get().getTerm() == prevLogTerm && prevEntry.get().getIndex() == getLastEntryIndex() ) { // The log is up to date return true; } } // 2. If an existing entry conflicts with a new one (same index but different terms), delete the existing entry and all // that follow it. if (!entries.isEmpty()) { for (EloquentRaftProto.LogEntry entry : entries) { Optional<EloquentRaftProto.LogEntry> potentiallyConflictingEntry = getEntryAtIndex(entry.getIndex()); // If we find a conflicting entry, then tructate after that if (potentiallyConflictingEntry.isPresent()) { if (potentiallyConflictingEntry.get().getTerm() != entry.getTerm()) { truncateLogAfterIndexInclusive(entry.getIndex()); break; } // If they're the same term, this is an opportunity to assert that it's the same transition else { assert(entry.toByteString().equals(potentiallyConflictingEntry.get().toByteString())); } } } } // 3. Append any new entries not already in the log if (!entries.isEmpty()) { // 3.1. Calculate how many entries we need to skip before appending the new entries long startIndex = entries.get(0).getIndex(); long lastKnownIndex = getLastEntryIndex(); // in the default cause, where we skip 0, lastKnownIndex = startIndex - 1 int skipEntries = (int) (lastKnownIndex - startIndex) + 1; assert (skipEntries >= 0); // 3.2. Add the entries for (int i = skipEntries; i < entries.size(); i++) { logEntries.add(entries.get(i)); // If an entry contains information about a new cluster membership, update our cluster membership immediately if (entries.get(i).getType() == EloquentRaftProto.LogEntryType.CONFIGURATION) { Optional<String> serverName = Optional.empty(); if (stateMachine instanceof KeyValueStateMachine) { serverName = ((KeyValueStateMachine)stateMachine).serverName; } log.info("{} - Reconfiguring cluster to {}", serverName.orElse("?"), entries.get(i).getConfigurationList()); latestQuorumMembers.clear(); latestQuorumMembers.addAll(entries.get(i).getConfigurationList()); } } // 3.3. Force a compaction if our log is longer than 100 entries long - this may be a noop if none of these hundred // entities is committed, but that's extremely rare in general. // if (snapshot.map(sn -> sn.lastIndex + COMPACTION_LIMIT <= this.commitIndex).orElse(commitIndex >= COMPACTION_LIMIT)) { if (this.logEntries.size() >= COMPACTION_LIMIT) { forceSnapshot(); } } return true; } finally { assertConsistency(); assert fast("appendEntries", timerStart); } } /** * This gets called from handleInstallSnapshotRPC() in EloquentRaftMember. It handles installing the snapshot and * updating our own logs appropriately. * * 1. If lastIndex is larger than the latest Snapshot's, then save the snapshot file and Raft state (lastIndex, * lastTerm, lastConfig). Discard any existing or partial snapshots * 2. If existing log entry has the same index and term as lastIndex, discard log up through lastIndex (but retain * following entries), and return. * 3. Otherwise, discard the entire log * 4. Reset state machine using snapshot contents, and load cluster config from the snapshot. * * @param snapshot the snapshot to install * @param now the current time, in case we want to mock it * * @return true if the snapshot got committed */ public boolean installSnapshot(Snapshot snapshot, long now) { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { // 1. If lastIndex is larger than the latest Snapshot's, then save the snapshot file and Raft state (lastIndex, // lastTerm, lastConfig). Discard any existing or partial snapshots. Otherwise return. if (!this.snapshot.isPresent() || snapshot.lastIndex > this.snapshot.get().lastIndex) { this.snapshot = Optional.of(snapshot); } else return false; // Note: committing up until the snapshot's last index here is actually incorrect - we can have entries at the // latest index with different term numbers than the snapshot, and therefore those should not be committed. // 2. If existing log entry has the same index and term as lastIndex, discard log up through lastIndex (but retain // following entries), and return. Optional<EloquentRaftProto.LogEntry> entry = getEntryAtIndex(snapshot.lastIndex); if (entry.isPresent() && entry.get().getTerm() == snapshot.lastTerm) { if (commitIndex < snapshot.lastIndex) { setCommitIndex(snapshot.lastIndex, now); } truncateLogBeforeIndexInclusive(snapshot.lastIndex); // We don't overwrite the state machine (step 4), since we have entries that are at least as up to date as this snapshot return true; } // 3. Otherwise, discard the entire log this.logEntries.clear(); // 4. Reset state machine using snapshot contents, and load cluster config from the snapshot. stateMachine.overwriteWithSerialized(snapshot.serializedStateMachine, now, this.pool); committedQuorumMembers.clear(); committedQuorumMembers.addAll(snapshot.lastClusterMembership); latestQuorumMembers.clear(); latestQuorumMembers.addAll(snapshot.lastClusterMembership); // Update the commit index setCommitIndex(snapshot.lastIndex, now); assertConsistency(); return true; } finally { assertConsistency(); assert fast("installSnapshot", timerStart); } } /** * This forces a log compaction step, where all the committed log entries are compacted away, and we backstop with a * single snapshot of the state machine. The resulting snapshot is returned. */ public Snapshot forceSnapshot() { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { Optional<EloquentRaftProto.LogEntry> optionalCommitEntry = getEntryAtIndex(commitIndex); // 1. If there are no entries that we can compact, then return a Snapshot without editing the log if (!optionalCommitEntry.isPresent()) { log.info("Snapshotting without any entries to snapshot. This means that our commitIndex has gotten more than "+COMPACTION_LIMIT+" behind our latest entry: commitIndex={}, number non-compacted entries={}, latestEntry={}", commitIndex, logEntries.size(), logEntries.size() > 0 ? logEntries.getLast().getIndex() : -1); // 1.1. If we've taken any previous snapshot, return that if (snapshot.isPresent()) { return snapshot.get(); } // 1.2. Otherwise, create a snapshot starting with no entries else { assert (commitIndex <= 1); return new Snapshot(stateMachine.serialize(), 0L, 0L, committedQuorumMembers); } } EloquentRaftProto.LogEntry commitEntry = optionalCommitEntry.get(); // 2. Install a snapshot of the last committed Snapshot snapshot = new Snapshot(stateMachine.serialize(), commitEntry.getIndex(), commitEntry.getTerm(), committedQuorumMembers); this.snapshot = Optional.of(snapshot); // 3. Compact the logs before this index truncateLogBeforeIndexInclusive(commitEntry.getIndex()); assert logEntries.size() <= 0 || (snapshot.lastIndex < logEntries.getLast().getIndex()); return snapshot; } finally { assertConsistency(); assert fast("forceSnapshot", timerStart); } } /** * <b>WARNING: UNSAFE!!!</b> * * This function violates the correctness principles of Raft, and should never be called in production code. * But, it's very useful for unit testing bizarre states Raft may accidentally end up in. * * @param log The new log to set. The old log is cleared in favor of these entries */ public void unsafeSetLog(List<EloquentRaftProto.LogEntry> log) { Object timerStart = Prometheus.startTimer(summaryTiming); if ("true".equals(System.getenv("ELOQUENT_PRODUCTION"))) { System.err.println("Called unsafeSetLog in production! Ignoring the call"); return; } assertConsistency(); try { this.logEntries.clear(); this.logEntries.addAll(log); this.commitIndex = 0; } finally { assertConsistency(); assert fast("unsafeSetLog", timerStart); } } /** * This retrieves a log entry at a given index. If we're asking for an index that's already been compacted, this * returns an empty entry. If we ask for an entry that's beyond the latest entry we know about, also return empty. * * This is package-private, since we want to be able to call it from tests, but otherwise it's perfectly internal. * * Also note that this is a linear-time operation with respect to the size of the log. * * @param index the index we'd like to request * * @return a log entry, unless it's already been compacted in which case we return empty */ Optional<EloquentRaftProto.LogEntry> getEntryAtIndex(long index) { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { // Some shortcuts if (this.logEntries.isEmpty()) { return Optional.empty(); } EloquentRaftProto.LogEntry first = this.logEntries.getFirst(); EloquentRaftProto.LogEntry last = this.logEntries.getLast(); if (index == first.getIndex()) { return Optional.of(first); } else if (index < first.getIndex()) { return Optional.empty(); } else if (index == last.getIndex()) { return Optional.of(last); } else if (index > last.getIndex()) { return Optional.empty(); } // Search over the deque Iterator<EloquentRaftProto.LogEntry> entries = index > (first.getIndex() + this.logEntries.size() / 2) ? this.logEntries.descendingIterator() : this.logEntries.iterator(); while (entries.hasNext()) { EloquentRaftProto.LogEntry entry = entries.next(); if (entry.getIndex() == index) { return Optional.of(entry); } } return Optional.empty(); } finally { assertConsistency(); assert fast("getEntryAtIndex", timerStart); } } /** * This deletes the entry at index, and all that follow it, from the log. * * @param index the index (inclusive) to delete from */ void truncateLogAfterIndexInclusive(long index) { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); assert(index > this.commitIndex); try { // 1. Check if this request is out of bounds if (index < 0) { assert(false) : "Cannot truncate to a negative log index"; index = 0; } // 2. If we have no log entries, then the one we're requesting has already been compacted if (logEntries.size() == 0) return; // 3. Get the index of the earliest entry that hasn't been compacted long earliestRecordedEntry = logEntries.getFirst().getIndex(); // 4. If we're requesting to trucate to an index that's earlier than our earliest log entry, then we need to exception if (index < earliestRecordedEntry) { assert(false) : "Cannot truncate beyond already compacted log entries"; index = earliestRecordedEntry; } // 5. Now we can check the offset into the logEntries, and truncate accordingly int logOffset = (int) (index - earliestRecordedEntry); while (logEntries.size() > logOffset) { logEntries.removeLast(); long newCommitIndex = Math.min(getLastEntryIndex(), this.commitIndex); assert(newCommitIndex >= this.commitIndex); this.commitIndex = newCommitIndex; } // 6. Recompute the cluster configuration Collection<String> latestConfiguration = null; // 6.1. Try to get the configuration from the log Iterator<EloquentRaftProto.LogEntry> iter = logEntries.descendingIterator(); while (iter.hasNext()) { EloquentRaftProto.LogEntry entry = iter.next(); if (entry.getConfigurationCount() > 0) { latestConfiguration = entry.getConfigurationList(); break; } } // 6.2. Try to get the configuration from the snapshot if (latestConfiguration == null && snapshot.isPresent()) { latestConfiguration = snapshot.get().lastClusterMembership; } // 6.3. Revert to the original configuration if (latestConfiguration == null) { latestConfiguration = initialQuorumMembers; } // 6.4. Update the quorum this.latestQuorumMembers.clear(); this.latestQuorumMembers.addAll(latestConfiguration); } finally { assertConsistency(); assert fast("truncateLogAfterIndexInclusive", timerStart); } } /** * This deletes the entry at index, and all that precede it, from the log. * * @param index the index (inclusive) to delete up to */ void truncateLogBeforeIndexInclusive(long index) { Object timerStart = Prometheus.startTimer(summaryTiming); assertConsistency(); try { // 1. Check if this request is out of bounds if (index < 0) throw new IndexOutOfBoundsException("Cannot truncate before a negative log index"); // 2. If we have no log entries, then the one we're requesting has already been compacted if (logEntries.size() == 0) return; // 3. Get the index of the earliest entry that hasn't been compacted long earliestRecordedEntry = logEntries.getFirst().getIndex(); // 4. If we're requesting to truncate up to an index that's earlier than our earliest log entry, then that's a no-op if (index < earliestRecordedEntry) { return; } // 5. Now we can check the offset into the logEntries, and truncate accordingly int logOffset = (int) (index - earliestRecordedEntry); for (int i = 0; i <= logOffset; i++) { assert (logEntries.size() > 0); logEntries.removeFirst(); } assert logEntries.size() <= 0 || logEntries.getFirst().getIndex() == index + 1; } finally { assertConsistency(); assert fast("truncateLogBeforeIndexInclusive", timerStart); } } /** * Assert that the log is in a self-consistent state. * * This should be called by every function to help us fail fast in case of errors. */ void assertConsistency() { assert this.commitIndex <= this.getLastEntryIndex() : "We've marked ourselves committed past our last entry: commitIndex=" + this.commitIndex + " lastEntry=" + this.getLastEntryIndex(); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RaftLog raftLog = (RaftLog) o; return commitIndex == raftLog.commitIndex && Objects.equals(new ArrayList<>(logEntries), new ArrayList<>(raftLog.logEntries)) && Objects.equals(stateMachine, raftLog.stateMachine) && Objects.equals(commitFutures, raftLog.commitFutures) && Objects.equals(snapshot, raftLog.snapshot) && Objects.equals(latestQuorumMembers, raftLog.latestQuorumMembers) && Objects.equals(committedQuorumMembers, raftLog.committedQuorumMembers) ; } /** {@inheritDoc} */ @Override public int hashCode() { return (int) commitIndex; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/RaftLogEntryLocation.java
package ai.eloquent.raft; import java.util.Objects; /** * A little helper class for a log entry location for a Raft log. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class RaftLogEntryLocation { /** The term of this log entry. */ public final long term; /** * The index of this log entry. * This is the global index of the entry, although it's tagged with a given term. */ public final long index; /** * The straightforward constructor. */ public RaftLogEntryLocation(long index, long term) { this.term = term; this.index = index; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RaftLogEntryLocation that = (RaftLogEntryLocation) o; return term == that.term && index == that.index; } /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(term, index); } /** {@inheritDoc} */ @Override public String toString() { return index + "@" + term; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/RaftState.java
package ai.eloquent.raft; import ai.eloquent.util.Span; import com.google.protobuf.ByteString; import java.util.*; import java.util.concurrent.ExecutorService; /** * The state of a Raft node. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class RaftState { /** * The leadership status of the given Raft node. * The other class encompasses citizens and shadows both. */ public enum LeadershipStatus { LEADER, CANDIDATE, OTHER } /* -------------------------------------------------------------------------- PERSISTENT STATE -------------------------------------------------------------------------- */ /** * The name (i.e., id) of this server. */ public final String serverName; /** * The Raft log. */ public final RaftLog log; /** * Latest term server has seen (initialized to 0 on first boot, increases monotonically. */ public long currentTerm = 0; /** * candidateId that received vote in the current term (or null if none) */ public Optional<String> votedFor = Optional.empty(); /** * ADDITION: the target size of the cluster, for auto-scaling. A value of -1 * disables auto-scaling altogether. */ public final int targetClusterSize; /* -------------------------------------------------------------------------- VOLATILE STATE (ALL) -------------------------------------------------------------------------- */ /** * The index of the highest log entry applied to state machine (initialized to 0, * increases monotonically). * This is a computed value, but appears here with the variables because it is part of * the core Raft spec as a variable. */ @SuppressWarnings("unused") public long lastApplied() { return this.log.getLastEntryIndex(); } /** * The leadership status of this node (leader / candidate / other) */ public volatile LeadershipStatus leadership = LeadershipStatus.OTHER; /* -------------------------------------------------------------------------- VOLATILE STATE (FOLLOWERS) -------------------------------------------------------------------------- */ /** * The timestamp of the last message received by this node from the leader. * This is used to compute the election timeout. */ public volatile long electionTimeoutCheckpoint = -1; // also used by candidates /** * The identity of the leader, if we know it. */ public volatile Optional<String> leader = Optional.empty(); /* -------------------------------------------------------------------------- VOLATILE STATE (CANDIDATES) -------------------------------------------------------------------------- */ /** * The timestamp of the last message received by this node from the leader. * This is used to compute the election timeout. */ public volatile Set<String> votesReceived = new HashSet<>(); /* -------------------------------------------------------------------------- VOLATILE STATE (LEADER) -------------------------------------------------------------------------- */ /** * For each server, the index of the next log entry to send to that server * (initialized to leader last log index + 1). */ public volatile Optional<Map<String, Long>> nextIndex = Optional.empty(); /** * For each server, the index of the highest log entry known to be replicated * on server. * (initialized to 0, increases monotonically). */ public volatile Optional<Map<String, Long>> matchIndex = Optional.empty(); /** * <p> * The timestamp of the last message received from each of the servers. * This value should never be absent for any server -- we initialize it optimistically. * </p> */ public volatile Optional<Map<String, Long>> lastMessageTimestamp = Optional.empty(); /** * <p> * The set of servers that have timed out, but we have already removed their transient * entries. This prevents us spamming the |ClearTransient| transition. * </p> */ public volatile Optional<Set<String>> alreadyKilled = Optional.empty(); /** * A cache on {@link RaftStateMachine#owners()}, since the call can potentially take * a long time. */ private volatile Set<String> cachedOwners = new HashSet<>(); /** * The timestamp at which we last refreshed {@link #cachedOwners}. */ private volatile long cachedOwnersTimestamp = Long.MIN_VALUE; /* -------------------------------------------------------------------------- METHODS -------------------------------------------------------------------------- */ /** * Create a new Raft state with only one node -- the given argument server name. */ public RaftState(String serverName, RaftStateMachine stateMachine, ExecutorService pool) { this(serverName, new RaftLog(stateMachine, Collections.singletonList(serverName), pool), -1); } /** * Create a new Raft state with the given target cluster size. If this size is -1, this becomes a single-node * Raft cluster with just this node. If this size is non-negative, it'll become a resizing cluster with the given * number of target nodes. */ public RaftState(String serverName, RaftStateMachine stateMachine, int targetClusterSize, ExecutorService pool) { this(serverName, new RaftLog(stateMachine, targetClusterSize >= 0 ? Collections.emptyList() : Collections.singletonList(serverName), pool), targetClusterSize); } /** Create a new Raft state with the given cluster members. This cluster is non-resizing. */ public RaftState(String serverName, RaftStateMachine stateMachine, Collection<String> clusterMembers, ExecutorService pool) { this(serverName, new RaftLog(stateMachine, clusterMembers, pool), -1); } /** The straightforward constructor */ public RaftState(String serverName, RaftLog log, int targetClusterSize) { this.serverName = serverName; this.log = log; if (!log.logEntries.isEmpty()) { this.currentTerm = log.getLastEntryTerm(); } this.targetClusterSize = targetClusterSize; } public RaftState(String serverName, RaftLog log) { this(serverName, log, 3); } /** * Create a copy of the Raft state at this moment in time. */ public RaftState copy() { log.assertConsistency(); RaftState copy = new RaftState(serverName, log.copy(), this.targetClusterSize); copy.currentTerm = this.currentTerm; copy.votedFor = this.votedFor; copy.leadership = this.leadership; copy.leader = this.leader; copy.nextIndex = this.nextIndex.map(HashMap::new); copy.matchIndex = this.matchIndex.map(HashMap::new); copy.lastMessageTimestamp = this.lastMessageTimestamp.map(HashMap::new); copy.alreadyKilled = this.alreadyKilled.map(HashSet::new); copy.electionTimeoutCheckpoint = this.electionTimeoutCheckpoint; copy.votesReceived = new HashSet<>(this.votesReceived); return copy; } /** * Index of the highest log entry know to be committed (initialized to 0, increases * monotonically). */ public long commitIndex() { return log.commitIndex; } /** * Bootstrap this cluster by adding this node to our own list of known nodes. * <b>This is inherently an unsafe operation!</b> * You should only call this function on one node, or else we may have split-brain * */ public void bootstrap(boolean force) { log.assertConsistency(); try { if (force || (this.targetClusterSize >= 0 && this.log.getQuorumMembers().isEmpty())) { // only if we need bootstrapping this.setCurrentTerm(this.currentTerm + (force ? 100000 : 1)); // Massively increase the term, which should force other boxes to acknowledge us as leader this.log.unsafeBootstrapQuorum(Collections.singleton(serverName)); } } finally { log.assertConsistency(); } } /** @see #bootstrap(boolean) */ public void bootstrap() { bootstrap(false); } /** * Set the current term for the state. * * @param term The new term. * * @see #currentTerm */ public void setCurrentTerm(long term) { log.assertConsistency(); assert term >= this.currentTerm: "The term number can never go backwards"; try { if (term > this.currentTerm) { // Clear the election state -- someone succeeded this.votesReceived.clear(); this.votedFor = Optional.empty(); } this.currentTerm = term; } finally { log.assertConsistency(); } } /** * Signal to the state that we have signs of life from a particular follower. * This updates {@link #lastMessageTimestamp}. * * @param followerName The name of the follower we observed life from. * @param now The current time. This is useful to be explicit about for mocks. */ public void observeLifeFrom(String followerName, long now) { log.assertConsistency(); try { assert isLeader() : "Cannot observe signs of life from a follower if we're not the leader!"; assert this.lastMessageTimestamp.isPresent() : "We think we're the leader, but have no lastMessageTimestamp"; lastMessageTimestamp.ifPresent(lastMessage -> lastMessage.compute(followerName, (key, currentValue) -> now)); alreadyKilled.ifPresent(killed -> killed.remove(followerName)); nextIndex.ifPresent(nextIndex -> nextIndex.computeIfAbsent(followerName, key -> log.getLastEntryIndex())); matchIndex.ifPresent(nextIndex -> nextIndex.computeIfAbsent(followerName, key -> 0L)); } finally { log.assertConsistency(); } } /** If true, we [think we] are the leader. */ public boolean isLeader() { log.assertConsistency(); return leadership == LeadershipStatus.LEADER; } /** If true, we are a candidate to become leader in an election. */ public boolean isCandidate() { log.assertConsistency(); return leadership == LeadershipStatus.CANDIDATE; } /** * Mark this state as a leader, setting the appropriate variables. * * @param now The current time, so we can initialize {@link #lastMessageTimestamp}. * This is mostly useful for mocks -- otherwise it should be {@link System#currentTimeMillis()}. */ public void elect(long now) { log.assertConsistency(); try { assert this.leadership != LeadershipStatus.LEADER : "Should not be able to elect if already a leader"; assert log.getQuorumMembers().contains(this.serverName) : "Cannot be elected leader if we're not in quorum"; if (this.leadership != LeadershipStatus.LEADER) { // don't double-elect this.leadership = LeadershipStatus.LEADER; HashMap<String, Long> nextIndex = new HashMap<>(5); HashMap<String, Long> matchIndex = new HashMap<>(5); HashMap<String, Long> lastMessageTimestamp = new HashMap<>(5); for (String node : log.getQuorumMembers()) { if (!node.equals(serverName)) { nextIndex.put(node, log.getLastEntryIndex() + 1); // Assume we're up to date matchIndex.put(node, 0L); // Assume no one has committed anything lastMessageTimestamp.put(node, now); // Assume everyone is online } } Set<String> owners = this.log.stateMachine.owners(); for (String stateOwner : owners) { if (!stateOwner.equals(this.serverName)) { lastMessageTimestamp.put(stateOwner, now); // Assume everyone who owns anything on the state is online } } this.nextIndex = Optional.of(nextIndex); this.matchIndex = Optional.of(matchIndex); this.lastMessageTimestamp = Optional.of(lastMessageTimestamp); this.alreadyKilled = Optional.of(new HashSet<>()); this.leader = Optional.of(serverName); } } finally { log.assertConsistency(); } } /** Step down from an election -- become a simple follower. */ public void stepDownFromElection() { log.assertConsistency(); try { this.leadership = LeadershipStatus.OTHER; if (this.leader.map(x -> x.equals(serverName)).orElse(false)) { this.leader = Optional.empty(); } this.nextIndex = Optional.empty(); this.lastMessageTimestamp = Optional.empty(); this.alreadyKilled = Optional.empty(); this.matchIndex = Optional.empty(); // Reset follower state this.electionTimeoutCheckpoint = -1; this.votesReceived.clear(); } finally { log.assertConsistency(); } } /** * Trigger a new election, and become a candidate. */ public void becomeCandidate() { log.assertConsistency(); try { // Error checks assert this.leadership == LeadershipStatus.OTHER : "Can only become a candidate from a non-candidate, non-leader state"; assert this.log.getQuorumMembers().contains(this.serverName) : "Cannot become a candidate if we are not in the quorum"; if (this.leadership != LeadershipStatus.OTHER) { this.stepDownFromElection(); } // just in case // Become a candidate if (this.leadership == LeadershipStatus.OTHER) { this.leadership = LeadershipStatus.CANDIDATE; assert votesReceived.isEmpty() : "Should not have any votes received when we start an election"; this.votesReceived.clear(); } } finally { log.assertConsistency(); } } /** * Reset the election timeout. That is, register that we've either just started * an election, or we've received a message from the leader that suggests that we * don't need to start an election. * * @param now The current timestamp. Should be {@link System#currentTimeMillis()} unless we're in a mock */ public void resetElectionTimeout(long now, Optional<String> leader) { log.assertConsistency(); try { // This is possible, just because the clock takes a while to process functions // assert this.electionTimeoutCheckpoint < 0 || this.electionTimeoutCheckpoint <= now : "Should not be able to move election timeout checkpoint backwards! now=" + now +"; checkpoint=" + this.electionTimeoutCheckpoint; if (this.electionTimeoutCheckpoint < 0 || this.electionTimeoutCheckpoint <= now) { // 1. Reset the election timeout this.electionTimeoutCheckpoint = now; // 2. Set the leader pointer // if (!leader.isPresent() || log.getQuorumMembers().contains(leader.get())) { // note[gabor]: this is ok in case of handoffs assert !leader.isPresent() || !leader.get().equals(this.serverName) || this.isLeader() || this.isCandidate() : "Can only set the leader to ourselves if we're a leader or candidate"; if (!this.leader.equals(leader)) { this.leader = leader; } // } } } finally { log.assertConsistency(); } } /** * @see #resetElectionTimeout(long, Optional) */ public void resetElectionTimeout(long now, String leader) { log.assertConsistency(); try { resetElectionTimeout(now, Optional.ofNullable(leader)); } finally { log.assertConsistency(); } } /** * If true, we should trigger an election. * If we have no timeout checkpoint, this starts the clock on the election timeout. * * @param now The current time, so that we can start the timer. * @param electionTimeoutMillisRange The timeout before we should trigger an election, as a range. * The chosen value in this range will be fixed for a given server + term. * * @return True if we should trigger an election. */ public boolean shouldTriggerElection(long now, Span electionTimeoutMillisRange) { log.assertConsistency(); try { if (this.electionTimeoutCheckpoint < 0) { // Case: this is our first check -- set the starting checkpoint, and wait for the timeout from here this.electionTimeoutCheckpoint = now; } if (!log.getQuorumMembers().contains(this.serverName)) { // Case: we're a shadow node -- never elect ourselves return false; } else if (isLeader()) { return false; // never trigger an election if we're the leader } else { // Case: check if we should trigger a timeout long seed = this.serverName.hashCode() ^ (new Random(this.currentTerm).nextLong()); long electionTimeoutMillis = new SplittableRandom(seed).nextLong(electionTimeoutMillisRange.begin, electionTimeoutMillisRange.end); return now - this.electionTimeoutCheckpoint > electionTimeoutMillis; } } finally { log.assertConsistency(); } } /** * Vote for a particular server as the leader. * * @param vote The server we voted for. */ public void voteFor(String vote) { log.assertConsistency(); try { assert !votedFor.isPresent() || votedFor.get().equals(vote); if (!votedFor.isPresent() || votedFor.get().equals(vote)) { // Vote for the node this.votedFor = Optional.ofNullable(vote); // If the node is us, receive a vote from us :) if (this.serverName.equals(vote)) { receiveVoteFrom(this.serverName); } if (vote != null && !vote.equals(this.serverName)) { // We're sure as hell not keeping our old leader -- may as well guess this candidate is the new leader this.leader = Optional.of(vote); } } } finally { log.assertConsistency(); } } /** * Receive a vote from a particular server. If we recieve a majority of the votes, * then we are considered elected. * * @param voter The server that voted for us. */ public void receiveVoteFrom(String voter) { log.assertConsistency(); try { if (log.getQuorumMembers().contains(voter)) { this.votesReceived.add(voter); } } finally { log.assertConsistency(); } } /** * This creates a new transition log entry, and appends it. Must be the current LEADER, or will throw an assert. * * @param transition the transition we'd like to add to the log. * @param newHospiceMember an optional new hospice member to add to the state machine. * * @return (term, index) of the new entry */ public RaftLogEntryLocation transition(Optional<byte[]> transition, Optional<String> newHospiceMember) { log.assertConsistency(); try { assert isLeader() : "Should only be able to transition as leader."; long newEntryIndex = log.getLastEntryIndex() + 1; EloquentRaftProto.LogEntry.Builder newLogEntry = EloquentRaftProto.LogEntry .newBuilder() .setIndex(newEntryIndex) .setTerm(currentTerm) .setType(EloquentRaftProto.LogEntryType.TRANSITION); transition.ifPresent(bytes -> newLogEntry.setTransition(ByteString.copyFrom(bytes))); newHospiceMember.ifPresent(newLogEntry::setNewHospiceMember); boolean success = log.appendEntries(log.getLastEntryIndex(), log.getLastEntryTerm(), Collections.singletonList(newLogEntry.build())); assert success : "Should always be able to add log entries on the leader"; this.matchIndex.ifPresent(map -> map.put(this.serverName, log.getLastEntryIndex())); // we're always matched up to date return new RaftLogEntryLocation(newEntryIndex, currentTerm); } finally { log.assertConsistency(); } } /** * Transition with only a regular transition, but no hospice member. * * @param transition The transition to implement. * * @return (term, index) of the new entry */ public RaftLogEntryLocation transition(byte[] transition) { return transition(Optional.of(transition), Optional.empty()); } /** * Commit up until a given index (inclusive). * Note that we can never commit backwards * * @param commitIndex The index to commit up to. * @param now The current time. */ public void commitUpTo(long commitIndex, long now) { log.assertConsistency(); try { assert commitIndex >= this.commitIndex() : "Cannot commit backwards!"; assert commitIndex <= this.log.getLastEntryIndex() : "Cannot commit beyond current log; commitIndex=" + commitIndex + " but last log entry=" + this.log.getLastEntryIndex(); if (commitIndex > this.commitIndex() && commitIndex <= this.log.getLastEntryIndex()) { log.setCommitIndex(commitIndex, now); } } finally { log.assertConsistency(); } } /** * This creates a new configuration log entry, and appends it. Must be the current LEADER, or will throw an assert. * * @param quorum the new quorum of nodes we'd like to have in the cluster. * @param force force the new configuration, even through it's an error. * @param now The current timestamp. * * @return (index, term) of the new entry */ public RaftLogEntryLocation reconfigure(Collection<String> quorum, boolean force, long now) { // Error checks log.assertConsistency(); try { assert isLeader() : "Can only reconfigure as leader"; boolean isSingletonCluster = log.latestQuorumMembers.size() == 1 && log.latestQuorumMembers.iterator().next().equals(this.serverName); Set<String> intersection = new HashSet<>(quorum); intersection.retainAll(log.getQuorumMembers()); assert force || ((intersection.equals(new HashSet<>(quorum)) || intersection.equals(log.getQuorumMembers())) && Math.abs(quorum.size() - log.getQuorumMembers().size()) == 1) : "We can only add or remove a single server at a time. proposed_config=" + quorum + " current_config=" + log.getQuorumMembers() + " intersection=" + intersection; // Enter the config long newEntryIndex = log.getLastEntryIndex() + 1; EloquentRaftProto.LogEntry newLogEntry = EloquentRaftProto.LogEntry .newBuilder() .setIndex(newEntryIndex) .setTerm(currentTerm) .setType(EloquentRaftProto.LogEntryType.CONFIGURATION) .addAllConfiguration(quorum) .build(); boolean success = log.appendEntries(log.getLastEntryIndex(), log.getLastEntryTerm(), Collections.singletonList(newLogEntry)); assert success; this.matchIndex.ifPresent(map -> map.put(this.serverName, log.getLastEntryIndex())); // we're always matched up to date // Special case: If we're entering a configuration with just ourselves, then immediately commit this entry // Addendum[gabor]: we can always remove ourselves from the quorum if ((isSingletonCluster && quorum.size() == 0) || (quorum.size() == 1 && quorum.iterator().next().equals(this.serverName))) { log.setCommitIndex(newEntryIndex, now); } // Ensure that everyone in the configuration has the associated metadata for (String voter : quorum) { if (!voter.equals(serverName)) { nextIndex.ifPresent(map -> map.computeIfAbsent(voter, key -> log.getLastEntryIndex() + 1)); matchIndex.ifPresent(map -> map.computeIfAbsent(voter, key -> 0L)); lastMessageTimestamp.ifPresent(map -> map.computeIfAbsent(voter, key -> now)); } } return new RaftLogEntryLocation(newEntryIndex, currentTerm); } finally { log.assertConsistency(); } } /** * @see #reconfigure(Collection, boolean, long) */ public RaftLogEntryLocation reconfigure(Collection<String> quorum, long now) { return reconfigure(quorum, false, now); } /** * Get the server to add to the cluster, if one should be added. * If no server should (or is available to) be added, we return {@link Optional#empty()}. * A server should be added if all of: * * <ol> * <li>{@link #targetClusterSize} is nonnegative, and</li> * <li>the current cluster size is less than {@link #targetClusterSize}.</li> * <li>the new server is not delinquent (i.e., is not timed out)</li> * </ol> * * @param now The current time in millis. This should be a value relative to {@link #lastMessageTimestamp} -- usually * the time on the transport (itself usually machine-local time). * @param maxLatency The maximum amount of time that we tolerate, in milliseconds, of the last heartbeat we received * from the node we're adding. * * * @return The server to add, or {@link Optional#empty()} if none should / can be added. */ public Optional<String> serverToAdd(long now, long maxLatency) { log.assertConsistency(); try { assert isLeader() : "Only the leader should be adding servers"; assert lastMessageTimestamp.isPresent() : "Leader should have a lastMessageTimestamp"; Set<String> hospice = log.stateMachine.getHospice(); if (targetClusterSize >= 0 && log.getQuorumMembers().size() < targetClusterSize) { // The cluster is the wrong size return lastMessageTimestamp.flatMap(heartbeats -> { // Find the most recently responding node that's not in the quorum long latestResponse = 0L; String argmaxName = null; for (Map.Entry<String, Long> entry : heartbeats.entrySet()) { if (!log.getQuorumMembers().contains(entry.getKey()) && !hospice.contains(entry.getKey()) && entry.getValue() > latestResponse) { latestResponse = entry.getValue(); argmaxName = entry.getKey(); } else if (hospice.contains(entry.getKey())) { System.err.println("node is in the hospice: " + entry.getKey()); } } // Make sure we wouldn't immediately want to remove the server if (argmaxName != null && !argmaxName.equals(serverName) && (now - latestResponse) < maxLatency) { // Return OK return Optional.of(argmaxName); } else { return Optional.empty(); } }); } else { // We don't want more servers return Optional.empty(); } } finally { log.assertConsistency(); } } /** * Get the server to remove from the cluster, if one should be removed. * If no server should be removed, we return {@link Optional#empty()}. * A server should be removed if both: * * <ol> * <li>{@link #targetClusterSize} is nonnegative, and</li> * <li>One of: * <ol> * <li>The current cluster is larger than {@link #targetClusterSize}, or</li> * <li>There exists a server that has been down for longer than the given timeout</li> * </ol> * </li> * </ol> * * @param now The current time in millis. This should be a value relative to {@link #lastMessageTimestamp} -- usually * the time on the transport (itself usually machine-local time). * @param timeout The maximum amount of time, in milliseconds, to keep a node in the configuration * before removing it from the cluster. * * @return The server to remove, or {@link Optional#empty()} if none should be removed. */ public Optional<String> serverToRemove(long now, long timeout) { log.assertConsistency(); try { assert isLeader() : "Only the leader should be removing servers"; assert lastMessageTimestamp.isPresent() : "Leader should have a lastMessageTimestamp"; if (targetClusterSize >= 0 && log.getQuorumMembers().size() > targetClusterSize) { // The cluster is the wrong size return lastMessageTimestamp.flatMap(heartbeats -> { // Find the least recently responding non-leader node that's in the quorum long mostDelinquentResponse = Long.MAX_VALUE; String argminName = null; for (Map.Entry<String, Long> entry : heartbeats.entrySet()) { if (log.getQuorumMembers().contains(entry.getKey()) && !entry.getKey().equals(serverName) && entry.getValue() < mostDelinquentResponse) { mostDelinquentResponse = entry.getValue(); argminName = entry.getKey(); } } return Optional.ofNullable(argminName); }); } else if (targetClusterSize >= 0) { // Check if there are any nodes that have exceeded the timeout return lastMessageTimestamp.flatMap(heartbeats -> { for (Map.Entry<String, Long> entry : heartbeats.entrySet()) { if (log.getQuorumMembers().contains(entry.getKey()) && !entry.getKey().equals(serverName) && (now - entry.getValue()) > timeout) { return Optional.of(entry.getKey()); } } return Optional.empty(); }); } else { // We explicitly don't want to allow resizing return Optional.empty(); } } finally { log.assertConsistency(); } } /** * Get the set of dead nodes that we should clear transient entries for. * This is only relevant for a {@link KeyValueStateMachine} where the notion of ownership * exists. * * @param now The current time in millis. This should be a value relative to {@link #lastMessageTimestamp} -- usually * the time on the transport (itself usually machine-local time). * @param timeout The maximum amount of time, in milliseconds, to keep a node "alive" * before clearing it's transient state from the Raft state. * * @return The set of nodes to remove. After returned, they are marked as already killed. */ public Set<String> killNodes(long now, long timeout) { // Error checks log.assertConsistency(); assert isLeader() : "Can only call deadNodes as leader"; assert lastMessageTimestamp.isPresent() : "Leader should have a lastMessageTimestamp"; assert alreadyKilled.isPresent() : "Leader should have alreadyKilled variable"; // Get nodes to kill if (log.stateMachine instanceof KeyValueStateMachine) { return lastMessageTimestamp.flatMap(lastMessageTimestamp -> alreadyKilled.map(alreadyKilled -> { Set<String> rtn = new HashSet<>(); if (now > cachedOwnersTimestamp + 1000) { cachedOwners = log.stateMachine.owners(); cachedOwnersTimestamp = now; } for (String owner : cachedOwners) { if (!owner.equals(this.serverName) && (now - lastMessageTimestamp.computeIfAbsent(owner, s -> now - timeout / 2)) > timeout && !alreadyKilled.contains(owner)) { rtn.add(owner); alreadyKilled.add(owner); } } return rtn; }) ).orElse(Collections.emptySet()); } else { return Collections.emptySet(); } } /** * If we could not kill the transient state on a node, we need to revive it with this function. * * @param node The node we have revived. * * @see #killNodes(long, long) */ public void revive(String node) { this.alreadyKilled.ifPresent( set -> set.remove(node) ); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RaftState raftState = (RaftState) o; return currentTerm == raftState.currentTerm && Objects.equals(serverName, raftState.serverName) && Objects.equals(log, raftState.log) && Objects.equals(votedFor, raftState.votedFor) && leadership == raftState.leadership && Objects.equals(leader, raftState.leader) && Objects.equals(nextIndex, raftState.nextIndex) && Objects.equals(matchIndex, raftState.matchIndex) && Objects.equals(electionTimeoutCheckpoint, raftState.electionTimeoutCheckpoint) && Objects.equals(votesReceived, raftState.votesReceived) && Objects.equals(alreadyKilled, raftState.alreadyKilled) && Objects.equals(lastMessageTimestamp, raftState.lastMessageTimestamp); } /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(serverName, log, currentTerm, votedFor, leadership, nextIndex, matchIndex, lastMessageTimestamp, electionTimeoutCheckpoint, votesReceived); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/RaftStateMachine.java
package ai.eloquent.raft; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ExecutorService; /** * This is the interface that any state machine needs to implement in order to be used with Theseus. */ public abstract class RaftStateMachine { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(KeyValueStateMachine.class); /** * The set of nodes that cannot be re-added to the cluster, even if we fall below the * minimum server size. * This is to prevent the case where we start shutting down boxes, and as one shuts down we * add it back to the quorum, which breaks Raft's consensus. */ private String[] hospice = new String[0]; /** * Get the current hospice. This is a copy of the hospice, * which means it is safe to mutate. */ public final synchronized Set<String> getHospice() { return new HashSet<>(Arrays.asList(hospice)); } /** * This serializes the state machine's current state into a proto that can be read from overwriteWithSerialized(). * * @return a proto of this state machine */ protected abstract ByteString serializeImpl(); /** * This serializes the state machine's current state into a proto that can be read from overwriteWithSerialized(). * * @return a proto of this state machine */ public final synchronized byte[] serialize() { ByteString payload = serializeImpl(); return EloquentRaftProto.StateMachine.newBuilder() .setPayload(payload) .addAllHospice(Arrays.asList(this.hospice)) .build().toByteArray(); } /** * This overwrites the current state of the state machine with a serialized proto. All the current state of the state * machine is overwritten, and the new state is substituted in its place. * * @param serialized the state machine to overwrite this one with, in serialized form * @param now the current time, in epoch millis. * @param pool an executor pool to run lock future commits on. */ protected abstract void overwriteWithSerializedImpl(byte[] serialized, long now, ExecutorService pool); /** * This overwrites the current state of the state machine with a serialized proto. All the current state of the state * machine is overwritten, and the new state is substituted in its place. * * @param serialized the state machine to overwrite this one with, in serialized form * @param now the current time, in epoch millis. * @param pool an executor pool to run lock future commits on. */ public final synchronized void overwriteWithSerialized(byte[] serialized, long now, ExecutorService pool) { try { EloquentRaftProto.StateMachine proto = EloquentRaftProto.StateMachine.parseFrom(serialized); this.hospice = proto.getHospiceList().toArray(new String[0]); this.overwriteWithSerializedImpl(proto.getPayload().toByteArray(), now, pool); } catch (InvalidProtocolBufferException e) { log.warn("Could not deserialize state machine; assuming it's in a legacy form"); this.hospice = new String[0]; this.overwriteWithSerializedImpl(serialized, now, pool); } } /** * The custom implementation of applying a transition */ protected abstract void applyTransition(byte[] transition, long now, ExecutorService pool); /** * This is responsible for applying a transition to the state machine. The transition is assumed to be coming in a * proto, and so is serialized as a byte array. * * @param transition The transition to apply, in serialized form * @param newHospiceMember A new hospice member to add to the blacklist. * @param now The current time, for mocking time in tests. * @param pool A pool that can be used for running the update listeners. */ final void applyTransition(Optional<byte[]> transition, Optional<String> newHospiceMember, long now, ExecutorService pool) { if (newHospiceMember.isPresent()) { assert !transition.isPresent() : "Got both a custom transition and hospice member in transition"; if (Arrays.stream(this.hospice).noneMatch(x -> x.equals(newHospiceMember.get()))) { // don't add a duplicate String[] newHospice; if (this.hospice.length >= 100) { newHospice = new String[this.hospice.length]; System.arraycopy(this.hospice, 1, newHospice, 0, this.hospice.length - 1); } else { newHospice = new String[this.hospice.length + 1]; System.arraycopy(this.hospice, 0, newHospice, 0, this.hospice.length); } newHospice[newHospice.length - 1] = newHospiceMember.get(); this.hospice = newHospice; } } else if (transition.isPresent()) { this.applyTransition(transition.get(), now, pool); } else { log.error("Got neither a hospice member or a custom transition in state machine transition"); } } /** * This is used for debugging log entries. Mostly ignored, but very useful for debugging fuzz tests that are failing. * * @param transition the transition to debug * @return a rendered string version of the transition */ public String debugTransition(byte[] transition) { return "<no debugging information>"; } /** * The set of nodes that own anything in the state machine. * This is an optional override, only for state machines that have a notion * of ownership. */ public Set<String> owners() { return Collections.emptySet(); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/RaftTransport.java
package ai.eloquent.raft; import ai.eloquent.util.SafeTimerTask; import ai.eloquent.util.Span; import java.io.IOException; import java.time.Duration; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiFunction; import java.util.function.Consumer; import ai.eloquent.raft.EloquentRaftProto.*; import ai.eloquent.util.Uninterruptably; /** * This encapsulates all the non-functional components in EloquentRaftMember so that the remaining code can be easily * unit-tested. That means this handles interfacing with EloquentChannel, as well as handling the timers. */ public interface RaftTransport { /** * The enumeration of different transport types. */ enum Type { /** Communicate over UDP and RPC. */ NET, /** A local transport -- only suitable for tests and single-box clusters. */ LOCAL } /** * Register a listener for RPCs. * This must be idempotent! * * @param listener The listener that should be called on all received RPC requests. */ void bind(RaftAlgorithm listener) throws IOException; /** * Get the collection of algorithms that have been bound to this transport. * This is primarily useful for unit testing. */ Collection<RaftAlgorithm> boundAlgorithms(); /** * Send an RPC request over the transport, expecting a reply. * * @param sender The name of the node sending the message. In many implementations, this is redundant. * @param destination The destination we are sending the message to. * This is a server name * on the same cluster as the node this transport is bound to. * @param message The message to send, as a {@link ai.eloquent.raft.EloquentRaftProto.RaftMessage}. * @param onResponseReceived The callback to run when a response is received from the server * for the RPC. Either this or onTimeout is always called. * @param onTimeout Called when no response is received in the given timeout threshold. * @param timeout The number of milliseconds to wait before considering an RPC timed out. */ void rpcTransport(String sender, String destination, EloquentRaftProto.RaftMessage message, Consumer<EloquentRaftProto.RaftMessage> onResponseReceived, Runnable onTimeout, long timeout); /** * Send an RPC request over the transport, not necessarily expecting a reply. * * @param sender The name of the node sending the message. In many implementations, this is redundant. * @param destination The destination we are sending the message to. * This is a server name * on the same cluster as the node this transport is bound to. * @param message The message to send, as a {@link ai.eloquent.raft.EloquentRaftProto.RaftMessage}. */ void sendTransport(String sender, String destination, EloquentRaftProto.RaftMessage message); /** * Broadcast an RPC request over the transport to all members of the cluster. * * @param sender The name of the node sending the message. In many implementations, this is redundant. * @param message The message to send, as a {@link ai.eloquent.raft.EloquentRaftProto.RaftMessage}. */ void broadcastTransport(String sender, EloquentRaftProto.RaftMessage message); /** * The expected delay, in milliseconds, for a round-trip on this transport. * This is used to calibrate the Raft algorithm, and to test the unit tests. */ Span expectedNetworkDelay(); /** For unit tests primarily -- most transports don't need to be started explicitly */ default void start() {} /** For unit tests primarily -- stop this transport and clean up if necessary. */ default void stop() {} /** * If true, we are allowed to block while running on this transport. This is useful * for, e.g., unit tests. But, in general, we should try to not block as much as posisble. * Defaults to false. */ default boolean threadsCanBlock() { return false; } /** * The current (local) time on the transport. This is usually {@link System#currentTimeMillis()} if this isn't * a mock. */ default long now() { return System.currentTimeMillis(); } /** Sleep for the given number of milliseconds. This is purely for mocking for tests. */ default void sleep(long millis) { Uninterruptably.sleep(millis); } /** Schedule an event every |period| seconds. This is an alias for {@link ai.eloquent.util.SafeTimer#scheduleAtFixedRate(SafeTimerTask, long, long)}, but mockable */ default void scheduleAtFixedRate(SafeTimerTask timerTask, long period) { RaftLifecycle.global.timer.get().scheduleAtFixedRate(timerTask, 0L, period); } /** Schedule an event every |period| seconds. This is an alias for {@link ai.eloquent.util.SafeTimer#schedule(SafeTimerTask, long)}, but mockable */ default void schedule(SafeTimerTask timerTask, long delay) { RaftLifecycle.global.timer.get().schedule(timerTask, delay); } /** Get a future. This is just a mockable alias for {@link CompletableFuture#get(long, TimeUnit)}. */ default <E> E getFuture(CompletableFuture<E> future, Duration timeout) throws InterruptedException, ExecutionException, TimeoutException { return future.get(timeout.toMillis(), TimeUnit.MILLISECONDS); } /** @see #sendTransport(String, String, EloquentRaftProto.RaftMessage) */ default void sendTransport(String sender, String destination, Object messageProto) { sendTransport(sender, destination, mkRaftMessage(sender, messageProto)); } /** @see #broadcastTransport(String, EloquentRaftProto.RaftMessage) */ default void broadcastTransport(String sender, Object messageProto) { broadcastTransport(sender, mkRaftMessage(sender, messageProto)); } /** @see #rpcTransport(String, String, EloquentRaftProto.RaftMessage, Consumer, Runnable, long) */ default void rpcTransport(String sender, String destination, Object message, Consumer<EloquentRaftProto.RaftMessage> onResponseReceived, Runnable onTimeout, long timeout) { rpcTransport(sender, destination, mkRaftRPC(sender, message), onResponseReceived, onTimeout, timeout); } /** @see #rpcTransport(String, String, EloquentRaftProto.RaftMessage, Consumer, Runnable, long) */ default <E> CompletableFuture<E> rpcTransportAsFuture(String sender, String destination, Object message, BiFunction<RaftMessage, Throwable, E> onResponseReceived, Consumer<Runnable> runMethod, long timeout) { CompletableFuture<E> future = new CompletableFuture<>(); rpcTransport( sender, destination, mkRaftRPC(sender, message), reply -> runMethod.accept(() -> future.complete(onResponseReceived.apply(reply, null))), () -> runMethod.accept(() -> future.complete(onResponseReceived.apply(null, new TimeoutException("Timed out RPC from " + sender + " to " + destination)))), timeout); return future; } /** @see #rpcTransport(String, String, EloquentRaftProto.RaftMessage, Consumer, Runnable, long) */ default <E> CompletableFuture<E> rpcTransportAsFuture(String sender, String destination, Object message, BiFunction<RaftMessage, Throwable, E> onResponseReceived, Consumer<Runnable> runMethod ) { return rpcTransportAsFuture(sender, destination, message, onResponseReceived, runMethod, 10000L); } /** * Create an RPC request to send over the transport. * This is tagged as an RPC, and then the appropriate request is populated in the resulting object. * * @param requestProto The proto of the request, which we'll wrap in a * {@linkplain ai.eloquent.raft.EloquentRaftProto.RaftMessage raft request}. * * @return A Raft RPC request proto we can send to the receiver. */ static EloquentRaftProto.RaftMessage mkRaftMessage(String sender, Object requestProto, boolean isRPC) { if (requestProto instanceof EloquentRaftProto.RaftMessage) { return ((EloquentRaftProto.RaftMessage) requestProto).toBuilder().setSender(sender).build(); } else if (requestProto instanceof EloquentRaftProto.RaftMessage.Builder) { return ((EloquentRaftProto.RaftMessage.Builder) requestProto).setSender(sender).build(); } EloquentRaftProto.RaftMessage.Builder request = EloquentRaftProto.RaftMessage.newBuilder() .setSender(sender) .setIsRPC(isRPC); if (requestProto instanceof AppendEntriesRequest) { // Append Entries request.setAppendEntries((AppendEntriesRequest) requestProto); } else if (requestProto instanceof InstallSnapshotRequest) { // Install Snapshot request.setInstallSnapshot((InstallSnapshotRequest) requestProto); } else if (requestProto instanceof RequestVoteRequest) { // Request Vote request.setRequestVotes((EloquentRaftProto.RequestVoteRequest) requestProto); } else if (requestProto instanceof AddServerRequest) { // Add Server request.setAddServer((AddServerRequest) requestProto); } else if (requestProto instanceof RemoveServerRequest) { // Remove Server request.setRemoveServer((RemoveServerRequest) requestProto); } else if (requestProto instanceof ApplyTransitionRequest) { // Apply Transition request.setApplyTransition((ApplyTransitionRequest) requestProto); } else if (requestProto instanceof AppendEntriesReply) { // RE: Append Entries request.setAppendEntriesReply((AppendEntriesReply) requestProto); } else if (requestProto instanceof InstallSnapshotReply) { // RE: Install Snapshot request.setInstallSnapshotReply((InstallSnapshotReply) requestProto); } else if (requestProto instanceof RequestVoteReply) { // RE: Request Votes request.setRequestVotesReply((RequestVoteReply) requestProto); } else if (requestProto instanceof AddServerReply) { // RE: Add Server request.setAddServerReply((AddServerReply) requestProto); } else if (requestProto instanceof RemoveServerReply) { // RE: Remove Server request.setRemoveServerReply((RemoveServerReply) requestProto); } else if (requestProto instanceof ApplyTransitionReply) { // RE: Apply Transition request.setApplyTransitionReply((ApplyTransitionReply) requestProto); } else { throw new IllegalStateException("Unknown request type for an RPC request: " + requestProto.getClass()); } return request.build(); } /** Create a non-blocking RPC. @see #mkRaftMessage(String, Object, boolean) */ static EloquentRaftProto.RaftMessage mkRaftMessage(String sender, Object requestProto) { return mkRaftMessage(sender, requestProto, false); } /** Create a blocking RPC. @see #mkRaftMessage(Object, boolean) */ static EloquentRaftProto.RaftMessage mkRaftRPC(String sender, Object requestProto) { return mkRaftMessage(sender, requestProto, true); } /** * Create a new transport of the given type. * * @param serverName The name of us (our server) * @param type The type of transport to create. * * @return A transport of the given type. * * @throws IOException Thrown if we could not create the given transport. */ static RaftTransport create(String serverName, RaftTransport.Type type) throws IOException { switch (type) { case NET: return new NetRaftTransport(serverName); case LOCAL: return new LocalTransport(true, true); default: throw new IOException("Uncreatable transport type: " + type); } } /** * For debugging, get the message type of a given message proto object. * * @param messageProto A raft message, of presumably unknown type. * * @return The type of the message */ default String messageType(RaftMessage messageProto) { if (messageProto.getAppendEntries() != AppendEntriesRequest.getDefaultInstance()) { // Append Entries return "append_entries"; } else if (messageProto.getRequestVotes() != RequestVoteRequest.getDefaultInstance()) { // Request Votes return "request_votes"; } else if (messageProto.getInstallSnapshot() != InstallSnapshotRequest.getDefaultInstance()) { // Install Snapshot return "install_snapshot"; } else if (messageProto.getAddServer() != AddServerRequest.getDefaultInstance()) { // Add Server return "add_server"; } else if (messageProto.getRemoveServer() != RemoveServerRequest.getDefaultInstance()) { // Remove Server return "remove_server"; } else if (messageProto.getApplyTransition() != ApplyTransitionRequest.getDefaultInstance()) { // Apply Transition return "apply_transition"; } else { return "unknown"; } } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/SingleThreadedRaftAlgorithm.java
package ai.eloquent.raft; import ai.eloquent.util.IdentityHashSet; import ai.eloquent.util.RuntimeInterruptedException; import ai.eloquent.util.SafeTimerTask; import ai.eloquent.util.StackTrace; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.annotation.Nonnull; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Function; /** * A {@link RaftAlgorithm} that wraps all of its calls in a queue to ensure that they * are executed single-threaded. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class SingleThreadedRaftAlgorithm implements RaftAlgorithm { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(SingleThreadedRaftAlgorithm.class); /** * An enum for a given task's priority */ private enum TaskPriority { CRITICAL, HIGH, LOW, ; } /** * A task that we're running synchronized on Raft. This is a runnable * and an exception handler. */ private static class RaftTask { /** The runnable for the task */ public final Runnable fn; /** The function to be called if we encounter an error */ public final Consumer<Throwable> onError; /** The priority of this task. */ public final TaskPriority priority; /** A human-readable name for this task. */ public final String debugString; /** The straightforward constructor */ private RaftTask(String debugString, TaskPriority priority, Runnable fn, Consumer<Throwable> onError) { this.fn = fn; this.onError = onError; this.debugString = debugString; this.priority = priority; } } /** * A Deque for {@linkplain RaftTask Raft Tasks} that handles different priorities * of messages. */ private static class RaftDeque implements Deque<RaftTask> { /** Critical priority messages */ private final ArrayDeque<RaftTask> criticalPriority = new ArrayDeque<>(); /** High priority messages */ private final ArrayDeque<RaftTask> highPriority = new ArrayDeque<>(); /** Low (normal) priority messages */ private final ArrayDeque<RaftTask> lowPriority = new ArrayDeque<>(); @Override public void addFirst(RaftTask raftTask) { switch (raftTask.priority) { case CRITICAL: this.criticalPriority.addFirst(raftTask); break; case HIGH: this.highPriority.addFirst(raftTask); break; case LOW: this.lowPriority.addFirst(raftTask); break; default: throw new IllegalArgumentException("Unhandled priority " + raftTask.priority + " for task " + raftTask.debugString); } } @Override public void addLast(RaftTask raftTask) { switch (raftTask.priority) { case CRITICAL: this.criticalPriority.addLast(raftTask); break; case HIGH: this.highPriority.addLast(raftTask); break; case LOW: this.lowPriority.addLast(raftTask); break; default: throw new IllegalArgumentException("Unhandled priority " + raftTask.priority + " for task " + raftTask.debugString); } } @Override public boolean offerFirst(RaftTask raftTask) { switch (raftTask.priority) { case CRITICAL: return this.criticalPriority.offerFirst(raftTask); case HIGH: return this.highPriority.offerFirst(raftTask); case LOW: if (this.lowPriority.size() > 10000) { return false; } return this.lowPriority.offerFirst(raftTask); default: throw new IllegalArgumentException("Unhandled priority " + raftTask.priority + " for task " + raftTask.debugString); } } @Override public boolean offerLast(RaftTask raftTask) { switch (raftTask.priority) { case CRITICAL: return this.criticalPriority.offerLast(raftTask); case HIGH: return this.highPriority.offerLast(raftTask); case LOW: if (this.lowPriority.size() > 10000) { return false; } return this.lowPriority.offerLast(raftTask); default: throw new IllegalArgumentException("Unhandled priority " + raftTask.priority + " for task " + raftTask.debugString); } } @Override public RaftTask removeFirst() { if (criticalPriority.peekFirst() != null) { return criticalPriority.removeFirst(); } else if (highPriority.peekFirst() != null) { return highPriority.removeFirst(); } else { return lowPriority.removeFirst(); } } @Override public RaftTask removeLast() { if (criticalPriority.peekLast() != null) { return criticalPriority.removeLast(); } else if (highPriority.peekLast() != null) { return highPriority.removeLast(); } else { return lowPriority.removeLast(); } } @Nullable @Override public RaftTask pollFirst() { if (criticalPriority.peekFirst() != null) { return criticalPriority.pollFirst(); } else if (highPriority.peekFirst() != null) { return highPriority.pollFirst(); } else { return lowPriority.pollFirst(); } } @Nullable @Override public RaftTask pollLast() { if (criticalPriority.peekLast() != null) { return criticalPriority.pollLast(); } else if (highPriority.peekLast() != null) { return highPriority.pollLast(); } else { return lowPriority.pollLast(); } } @Override public RaftTask getFirst() { if (criticalPriority.peekFirst() != null) { return criticalPriority.getFirst(); } else if (highPriority.peekFirst() != null) { return highPriority.getFirst(); } else { return lowPriority.getFirst(); } } @Override public RaftTask getLast() { if (criticalPriority.peekLast() != null) { return criticalPriority.getLast(); } else if (highPriority.peekLast() != null) { return highPriority.getLast(); } else { return lowPriority.getLast(); } } @Override public RaftTask peekFirst() { if (criticalPriority.peekFirst() != null) { return criticalPriority.peekFirst(); } else if (highPriority.peekFirst() != null) { return highPriority.peekFirst(); } else { return lowPriority.peekFirst(); } } @Override public RaftTask peekLast() { if (criticalPriority.peekLast() != null) { return criticalPriority.peekLast(); } else if (highPriority.peekLast() != null) { return highPriority.peekLast(); } else { return lowPriority.peekLast(); } } @Override public boolean removeFirstOccurrence(Object o) { return criticalPriority.removeFirstOccurrence(o) || highPriority.removeFirstOccurrence(o) || lowPriority.removeFirstOccurrence(o); } @Override public boolean removeLastOccurrence(Object o) { return lowPriority.removeLastOccurrence(o) || highPriority.removeLastOccurrence(o) || criticalPriority.removeLastOccurrence(o); } @Override public boolean add(RaftTask raftTask) { this.addLast(raftTask); return true; } @Override public boolean offer(RaftTask raftTask) { return this.offerLast(raftTask); } @Override public RaftTask remove() { return this.removeFirst(); } @Override public RaftTask poll() { return this.pollFirst(); } @Override public RaftTask element() { return this.getFirst(); } @Override public RaftTask peek() { return this.peekFirst(); } @Override public void push(RaftTask raftTask) { this.addFirst(raftTask); } @Override public RaftTask pop() { return this.removeFirst(); } @Override public boolean remove(Object o) { return this.removeFirstOccurrence(o); } @Override public boolean containsAll(@Nonnull Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean addAll(@Nonnull Collection<? extends RaftTask> c) { for (RaftTask t : c) { this.add(t); } return true; } @Override public boolean removeAll(@Nonnull Collection<?> c) { for (Object t : c) { this.remove(t); } return true; } @Override public boolean retainAll(@Nonnull Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { this.criticalPriority.clear(); this.highPriority.clear(); this.lowPriority.clear(); } @Override public boolean contains(Object o) { return this.criticalPriority.contains(o) || this.highPriority.contains(o) || this.lowPriority.contains(o); } @Override public int size() { return this.criticalPriority.size() + this.highPriority.size() + this.lowPriority.size(); } @Override public boolean isEmpty() { return this.criticalPriority.isEmpty() && this.highPriority.isEmpty() && this.lowPriority.isEmpty(); } @Nonnull @Override public Iterator<RaftTask> iterator() { Deque<RaftTask> all = new ArrayDeque<>(this.criticalPriority); all.addAll(this.highPriority); all.addAll(this.lowPriority); return all.iterator(); } @Nonnull @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Nonnull @Override public <T> T[] toArray(@Nonnull T[] a) { throw new UnsupportedOperationException(); } @Nonnull @Override public Iterator<RaftTask> descendingIterator() { throw new UnsupportedOperationException(); } } /** * The Raft algorithm we're actually running, wrapped in a single-threaded * environment. */ public final RaftAlgorithm impl; /** * The thread that's going to be driving the Raft algorith, */ @SuppressWarnings("FieldCanBeLocal") private final Thread raftThread; /** * The {@link RaftTask#debugString} of the currently running task. * This is used primarily in {@link #flush(Runnable)} to make * sure we don't mark ourselves as flushed if there's a task * currently in progress. */ private Optional<String> taskRunning = Optional.empty(); /** * The marker for whether the raft algorithm is alive. */ private boolean alive = true; /** * The queue of tasks for Raft to pick up on. */ private final RaftDeque raftTasks = new RaftDeque(); /** * The count of futures that we're still waiting on */ private final Set<CompletableFuture> waitingForFutures = new IdentityHashSet<>(); /** * The pool that'll be used to run any Future that can see into the outside world. * This is often the same as {@link RaftLog#pool}. */ private final ExecutorService boundaryPool; /** * JUST FOR TESTS: Only used in LocalTransport * * We need this in order to prevent time from slipping while boundary pool threads are created but have not yet * started. */ public static final AtomicInteger boundaryPoolThreadsWaiting = new AtomicInteger(0); /** @see RaftTransport#threadsCanBlock() */ private final boolean threadsCanBlock; /** * Create a single-thread driven Raft algorithm from an implementing instance. * * @param impl The implemeting algorithm. See {@link #impl}. * @param boundaryPool The boundary pool. See {@link #boundaryPool}. */ public SingleThreadedRaftAlgorithm(RaftAlgorithm impl, ExecutorService boundaryPool) { this.impl = impl; this.threadsCanBlock = impl.getTransport().threadsCanBlock(); this.raftThread = new Thread( () -> { if (impl instanceof EloquentRaftAlgorithm) { ((EloquentRaftAlgorithm) impl).setDrivingThread(r -> { synchronized (raftTasks) { raftTasks.offer(new RaftTask("EloquentRaftAlgorithm Callback", TaskPriority.CRITICAL, r, e -> log.warn("Error in queued task", e))); raftTasks.notifyAll(); } }); } try { while (alive) { RaftTask task; try { synchronized (raftTasks) { taskRunning = Optional.empty(); raftTasks.notifyAll(); while (raftTasks.isEmpty()) { raftTasks.wait(1000); if (!alive) { return; } } task = raftTasks.poll(); taskRunning = Optional.of(task.debugString); } try { task.fn.run(); } catch (Throwable t) { task.onError.accept(t); } } catch (Throwable t) { log.warn("Caught exception ", t); } } } finally { synchronized (raftTasks) { // Clean up any leftovers raftTasks.forEach(t -> t.onError.accept(new RuntimeException("SingleThreadedRaftAlgorithm main thread killed from killMainThread(), so this will never complete"))); raftTasks.clear(); waitingForFutures.forEach(completableFuture -> completableFuture.completeExceptionally(new RuntimeException("SingleThreadedRaftAlgorithm main thread killed from killMainThread(), so this will never complete"))); waitingForFutures.clear(); } } }); this.raftThread.setPriority(Math.max(Thread.MIN_PRIORITY, Thread.MAX_PRIORITY - 2)); this.raftThread.setDaemon(false); this.raftThread.setName("raft-control-" + impl.serverName()); this.raftThread.setUncaughtExceptionHandler((t, e) -> log.warn("Caught exception on {}:", t.getName(), e)); this.raftThread.start(); this.boundaryPool = boundaryPool; } /** * Return the number of tasks we have queued to be executed by Raft. */ public int queuedTaskCount() { synchronized (this.raftTasks) { return this.raftTasks.size(); } } /** * Run a given function, returning a completable future for when this function is complete. * Note that this completable future completes <b>on the raft thread</b>, and therefore * should not be exposed to the outside world. * * @param debugName A debug name for this task. * @param priority The priority for this task * @param fn The function we are running. Typically, a {@link RaftAlgorithm} method. * @param <E> The return type of our function. * * @return A future for tracking when we actually have finished scheduling and running * this function. */ private <E> CompletableFuture<E> execute(String debugName, TaskPriority priority, Function<RaftAlgorithm, E> fn) { log.trace("{} - [{}] Executing as Future {}", this.serverName(), getTransport().now(), debugName); if (Thread.currentThread() == raftThread) { // don't queue if we're on the raft thread return CompletableFuture.completedFuture(fn.apply(this.impl)); } if (!alive) { throw new IllegalStateException("Node is dead -- failing the future"); } CompletableFuture<E> future = new CompletableFuture<>(); Runnable task = () -> future.complete(fn.apply(this.impl)); Consumer<Throwable> onError = future::completeExceptionally; synchronized (raftTasks) { raftTasks.offer(new RaftTask(debugName, priority, task, onError)); raftTasks.notifyAll(); } return future; } /** * Run a given function, returning a completable future for when this function is complete. * Unlike {@link #execute(String, TaskPriority, Function)}, this returns a <b>safe future to be show to the * outside world</b>. * * @param debugName A debug name for this task. * @param priority The priority for this task * @param fn The function we are running. Typically, a {@link RaftAlgorithm} method. * @param <E> The return type of our function. * * @return A future for tracking when we actually have finished scheduling and running * this function. */ private <E> CompletableFuture<E> executeFuture(String debugName, TaskPriority priority, Function<RaftAlgorithm, CompletableFuture<E>> fn) { // 1. Check if we should execute directly log.trace("{} - [{}] Executing as Composite Future {}", this.serverName(), getTransport().now(), debugName); if (!alive) { throw new IllegalStateException("Node is dead -- failing the future"); } if (Thread.currentThread().getId() == raftThread.getId()) { // don't queue if we're on the raft thread return fn.apply(this.impl); } CompletableFuture<E> future = new CompletableFuture<>(); // 2. Define the timeout for the future CompletableFuture<CompletableFuture<E>> futureOfFuture = execute(debugName, priority, fn); final SafeTimerTask timeoutResult = new SafeTimerTask() { @Override public void runUnsafe() { CompletableFuture<E> result = futureOfFuture.getNow(null); if (result == null) { // note[gabor]: OK to fail on this thread; they'll defer to boundary pool in the exception handling below futureOfFuture.completeExceptionally(new TimeoutException("Timed out executeFuture() (never got future)")); } else if (!result.isDone()) { // note[gabor]: OK to fail on this thread; they'll defer to boundary pool in the exception handling below result.completeExceptionally(new TimeoutException("Timed out executeFuture() (never completed future)")); } } }; synchronized (raftTasks) { waitingForFutures.add(futureOfFuture); } futureOfFuture.whenComplete((CompletableFuture<E> result, Throwable t) -> execute(debugName, priority, raft -> { // ensure that we're on the controller thread // note: this must be running on the Raft control thread if (Thread.currentThread().getId() != raftThread.getId()) { log.warn("Future of future should be completing on the Raft control thread; running on {} instead", Thread.currentThread()); } // 3. Check our future // 3.1. Check that we got our future OK from the Raft main thread if (t != null) { boundaryPoolThreadsWaiting.incrementAndGet(); // see canonical deadlock below -- we need to handle it here as well boundaryPool.submit(() -> { try { future.completeExceptionally(t); } finally { boundaryPoolThreadsWaiting.decrementAndGet(); } }); return; } // 3.2. Register our future appropriately synchronized (raftTasks) { waitingForFutures.remove(futureOfFuture); waitingForFutures.add(result); } // 4. Register the completion on the boundary pool result.whenComplete((E r, Throwable t2) -> { // note: this is likely running on the Raft control thread if (t2 == null && Thread.currentThread().getId() != raftThread.getId()) { // ok to fail on timer thread -- we defer to boundary thread below log.warn("Future of future's implementation should be completing on the Raft control thread; running on {} instead", Thread.currentThread().getId()); } // 4.1. Cancel the timeout synchronized (timeoutResult) { timeoutResult.cancel(); } // JUST FOR TESTS: this helps resolve a deadlock detailed below boundaryPoolThreadsWaiting.incrementAndGet(); // There's a race condition here that's tricky and hard to remove - and only shows up in the tests // The time between the above line ^ and the below line v must be 0 for the tests, but of course can't be. // // EXAMPLE: If we make an RPC call from a follower to the leader, all the network messages can propagate around // synchronously, and we'll still end up timing out the RPC call because time can slip before the boundary pool // task wakes up. // // The solution is to have LocalTransport's timekeeper thread spin till SingleThreadedRaftAlgorithm.boundaryPoolThreadsWaiting is 0. // // 4.2. Define the function to complete the future Runnable completeFuture = () -> { // make sure the future is run from the boundary pool try { if (r != null) { future.complete(r); } else if (t2 != null) { future.completeExceptionally(t2); } else { log.warn("whenComplete() called with a null result and a null exception, this should be impossible!"); future.completeExceptionally(new RuntimeException("This should be impossible!")); } } finally { synchronized (raftTasks) { waitingForFutures.remove(result); } boundaryPoolThreadsWaiting.decrementAndGet(); } }; // 4.3. Schedule the completion on the pool try { boundaryPool.submit(completeFuture); } catch (Throwable boundaryPoolError) { log.error("We got an exception submitting a task to the boundary pool from SingleThreadedRaftAlgorithm. Falling back to a daemon thread.", boundaryPoolError); Thread thread = new Thread(completeFuture); thread.setDaemon(true); thread.setName("boundary-pool-fallback"); thread.setPriority(Thread.NORM_PRIORITY); thread.start(); } }); }) ); // 5. Schedule the timeout try { synchronized (timeoutResult) { if (!timeoutResult.cancelled) { getTransport().schedule(timeoutResult, impl.electionTimeoutMillisRange().end + 100); } } } catch (Throwable timeoutError) { log.warn("Could not schedule timeout future: ", timeoutError); } // 6. Return return future; } /** * Run a given function, dumping the result into the void. * This is useful for void return type methods on a {@link RaftAlgorithm}. * * @param debugName A debug name for this task. * @param priority The priority for this task * @param fn The function we are running. Typically, a {@link RaftAlgorithm} method. */ private void execute(String debugName, TaskPriority priority, Consumer<RaftAlgorithm> fn) { log.trace("{} - [{}] Executing {}", this.serverName(), getTransport().now(), debugName); if (Thread.currentThread().getId() == raftThread.getId()) { // don't queue if we're on the raft thread fn.accept(this.impl); return; } AtomicBoolean done = new AtomicBoolean(false); synchronized (raftTasks) { if (!alive) { log.debug("Node is dead -- ignoring any messages to it"); return; } if (!raftTasks.offer(new RaftTask(debugName, priority, () -> { try { fn.accept(this.impl); } finally { synchronized (done) { done.set(true); done.notifyAll(); } } }, (e) -> { log.warn("Got exception running Raft method {}", debugName, e); synchronized (done) { done.set(true); done.notifyAll(); } }))) { log.warn("Dropping task {} due to size constraints (queue size={})", debugName, raftTasks.size()); } raftTasks.notifyAll(); } if (this.threadsCanBlock) { synchronized (done) { if (!done.get()) { try { done.wait(1000); } catch (InterruptedException e) { log.warn("Task seems to be backed up"); } } } } } /** {@inheritDoc} */ @Override public RaftState state() { try { return execute("state", TaskPriority.LOW, RaftAlgorithm::state).get(30, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.warn("Could not get RaftState -- returning unlocked version as a failsafe"); return impl.state(); } } /** {@inheritDoc} */ @Override public RaftState mutableState() { return impl.mutableState(); // note[gabor] don't run as a future -- this is mutable anyways } /** {@inheritDoc} */ @Override public RaftStateMachine mutableStateMachine() { return impl.mutableStateMachine(); // note[gabor] don't run as a future -- this is mutable anyways } /** {@inheritDoc} */ @Override public long term() { return impl.term(); } /** {@inheritDoc} */ @Override public String serverName() { return impl.serverName(); // note[gabor] don't run as a future -- this should never change } /** {@inheritDoc} */ @Override public void broadcastAppendEntries(long now) { execute("broadcastAppendEntries", TaskPriority.HIGH, (Consumer<RaftAlgorithm>) x -> x.broadcastAppendEntries(now)); } /** {@inheritDoc} */ @Override public void sendAppendEntries(String target, long nextIndex) { execute("sendAppendEntries", TaskPriority.HIGH,(Consumer<RaftAlgorithm>) x -> x.sendAppendEntries(target, nextIndex)); } /** {@inheritDoc} */ @Override public void receiveAppendEntriesRPC(EloquentRaftProto.AppendEntriesRequest heartbeat, Consumer<EloquentRaftProto.RaftMessage> replyLeader, long now) { execute("receiveAppendEntriesRPC", TaskPriority.HIGH, (Consumer<RaftAlgorithm>) x -> x.receiveAppendEntriesRPC(heartbeat, replyLeader, now)); } /** {@inheritDoc} */ @Override public void receiveAppendEntriesReply(EloquentRaftProto.AppendEntriesReply reply, long now) { execute("receiveAppendEntriesReply", TaskPriority.HIGH, (Consumer<RaftAlgorithm>) x -> x.receiveAppendEntriesReply(reply, now)); } /** {@inheritDoc} */ @Override public void receiveInstallSnapshotRPC(EloquentRaftProto.InstallSnapshotRequest snapshot, Consumer<EloquentRaftProto.RaftMessage> replyLeader, long now) { execute("receiveInstallSnapshotRPC", TaskPriority.HIGH, (Consumer<RaftAlgorithm>) x -> x.receiveInstallSnapshotRPC(snapshot, replyLeader, now)); } /** {@inheritDoc} */ @Override public void receiveInstallSnapshotReply(EloquentRaftProto.InstallSnapshotReply reply, long now) { execute("receiveInstallSnapshotReply", TaskPriority.HIGH, (Consumer<RaftAlgorithm>) x -> x.receiveInstallSnapshotReply(reply, now)); } /** {@inheritDoc} */ @Override public void triggerElection(long now) { execute("triggerElection", TaskPriority.LOW, (Consumer<RaftAlgorithm>) x -> x.triggerElection(now)); } /** {@inheritDoc} */ @Override public void receiveRequestVoteRPC(EloquentRaftProto.RequestVoteRequest voteRequest, Consumer<EloquentRaftProto.RaftMessage> replyLeader, long now) { execute("receiveRequestVoteRPC", TaskPriority.CRITICAL, (Consumer<RaftAlgorithm>) x -> x.receiveRequestVoteRPC(voteRequest, replyLeader, now)); } /** {@inheritDoc} */ @Override public void receiveRequestVotesReply(EloquentRaftProto.RequestVoteReply reply, long now) { execute("receiveRequestVotesReply", TaskPriority.CRITICAL, (Consumer<RaftAlgorithm>) x -> x.receiveRequestVotesReply(reply, now)); } /** {@inheritDoc} */ @Override public CompletableFuture<EloquentRaftProto.RaftMessage> receiveAddServerRPC(EloquentRaftProto.AddServerRequest addServerRequest, long now) { return executeFuture("receiveAddServerRPC", TaskPriority.LOW, x -> x.receiveAddServerRPC(addServerRequest, now)); } /** {@inheritDoc} */ @Override public CompletableFuture<EloquentRaftProto.RaftMessage> receiveRemoveServerRPC(EloquentRaftProto.RemoveServerRequest removeServerRequest, long now) { return executeFuture("receciveRemoveServerRPC", TaskPriority.HIGH, x -> x.receiveRemoveServerRPC(removeServerRequest, now)); } /** {@inheritDoc} */ @Override public CompletableFuture<EloquentRaftProto.RaftMessage> receiveApplyTransitionRPC(EloquentRaftProto.ApplyTransitionRequest transition, long now) { return executeFuture("receiveApplyTransitionRPC", TaskPriority.LOW, x -> x.receiveApplyTransitionRPC(transition, now)); } /** {@inheritDoc} */ @Override public boolean bootstrap(boolean force) { try { return execute("bootstrap", TaskPriority.CRITICAL, (Function<RaftAlgorithm, Boolean>) x -> x.bootstrap(force)).get(30, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.warn("Could not bootstrap -- returning unlocked version as a failsafe"); return impl.bootstrap(force); } } /** {@inheritDoc} */ @Override public void stop(boolean kill) { // Call the implementing algorithm's stop execute("stop", TaskPriority.LOW, (Consumer<RaftAlgorithm>) x -> x.stop(kill)); flush(() -> {}); // Stop our thread synchronized (raftTasks) { this.alive = false; this.boundaryPool.shutdown(); // Wake up the main thread so it can die this.raftTasks.notifyAll(); this.waitingForFutures.forEach(completableFuture -> completableFuture.completeExceptionally(new RuntimeException("killMainThread() killed this future"))); } } /** {@inheritDoc} */ @Override public boolean isRunning() { try { return execute("isRunning", TaskPriority.LOW, RaftAlgorithm::isRunning).get(30, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.warn("Could not check if Raft is running -- returning unlocked version as a failsafe"); return impl.isRunning(); } } /** {@inheritDoc} */ @Override public void heartbeat(long now) { execute("heartbeat", TaskPriority.HIGH, (Consumer<RaftAlgorithm>) x -> x.heartbeat(now)); } /** {@inheritDoc} */ @Override public void receiveBadRequest(EloquentRaftProto.RaftMessage message) { execute("receiveBadRequest", TaskPriority.LOW, (Consumer<RaftAlgorithm>) x -> x.receiveBadRequest(message)); } /** {@inheritDoc} */ @Override public Optional<RaftLifecycle> lifecycle() { return impl.lifecycle(); // note[gabor] don't run as a future -- this should be final } @Override public RaftTransport getTransport() { return impl.getTransport(); } /** * Flush the task queue. This is useful primarily for unit tests where * we're mocking time. * * @param additionalCriteria A function to run once things are flushed, after * which we should flush again. That is, make sure both * the transport is flushed, and this additional criteria * is also met (i.e., has run) when the algorithm is flushed. */ public void flush(Runnable additionalCriteria) { boolean isEmpty; // 1. Run the critera and check for emptiness additionalCriteria.run(); synchronized (this.raftTasks) { isEmpty = this.raftTasks.isEmpty() && !this.taskRunning.isPresent(); } // 2. Our loop while (!isEmpty) { // 2.1. Flush synchronized (this.raftTasks) { while (!this.raftTasks.isEmpty()) { try { this.raftTasks.wait(100); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } } } // 2.2. Rerun criteria additionalCriteria.run(); synchronized (this.raftTasks) { isEmpty = this.raftTasks.isEmpty() && !this.taskRunning.isPresent(); } } } /** * Get errors from this Raft algorithm */ public List<String> errors() { List<String> errors = new ArrayList<>(); // 1. Check queued tasks int queuedTasks = this.queuedTaskCount(); if (queuedTasks > 5) { errors.add("" + queuedTasks + " tasks queued on Raft control thread (> threshold of 5)." + " Running task is '" + this.taskRunning.orElse("<unknown>") + "'" + " with a stack trace of:\n" + new StackTrace(this.raftThread.getStackTrace()) ); } // 2. Get algorithm errors if (impl instanceof EloquentRaftAlgorithm) { if (Thread.currentThread().getId() == raftThread.getId()) { // don't queue if we're on the raft thread return ((EloquentRaftAlgorithm) impl).errors(); } CompletableFuture<List<String>> future = new CompletableFuture<>(); Runnable task = () -> future.complete(((EloquentRaftAlgorithm) this.impl).errors()); Consumer<Throwable> onError = future::completeExceptionally; synchronized (raftTasks) { raftTasks.offer(new RaftTask("errors", TaskPriority.LOW, task, onError)); raftTasks.notifyAll(); } try { errors.addAll(future.get(10, TimeUnit.SECONDS)); } catch (InterruptedException | ExecutionException | TimeoutException e) { errors.add("Could not get errors from implementing algorithm"); } } // Return return errors; } /** * Kill this Raft on GC */ @Override protected void finalize() throws Throwable { super.finalize(); stop(true); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/Theseus.java
package ai.eloquent.raft; import ai.eloquent.error.RaftErrorListener; import ai.eloquent.util.Lazy; import ai.eloquent.util.SafeTimerTask; import ai.eloquent.util.TimerUtils; import ai.eloquent.web.TrackedExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.InetAddress; import java.net.UnknownHostException; import java.time.Duration; import java.util.*; import java.util.concurrent.*; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; /** * This is the high-level user-facing API for RAFT. It's designed to appear simple to end-users. The key reason we need * this as opposed to an off-the-shelf implementation is that we want it to be embedded in an application that runs on * Kubernetes, and that imposes a key difference in assumptions over the original RAFT algorithm: boxes that fail will * be replaced, not rebooted. We want this to be embedded so that our implementation for distributed locks will * automatically release the lock of a box that disconnects from the cluster. * * Our core design goals: * * - Use EloquentChannel as the transport layer, to avoid flaky networking on Kubernetes * - Don't persist state to disk, since boxes that fail will be replaced, not rebooted. * - Keep it simple * */ public class Theseus { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(Theseus.class); /** * This holds a lock that is expected to live longer than the duration of a single method call. Usually this lock is * associated with a resource that the holder is responsible for. Because forgetting/failing to release long lived * locks can be catastrophic, this class packages up a number of safegaurds to ensure that the lock does eventually * get released. Since locks auto-release when their owner disconnects from the cluster, this can safely be a part of * Theseus, since as soon as Theseus closes these locks no longer need cleaning up anyways. */ public interface LongLivedLock extends AutoCloseable { /** * Returns the name of the lock that is held. */ String lockName(); /** * Returns true if the lock represented is still certainly held. * If this is true, {@link #isPerhapsHeld()} is always true as well, but not * visa versa. */ boolean isCertainlyHeld(); /** * Returns true if the lock represented has a chance of being held. * This can be true even when {@link #isCertainlyHeld()} is false, in cases where we are in the process * of releasing the lock. * Note that unlike {@link #isCertainlyHeld()}, this may never revert to false in rare cases when we cannot talk * to Raft effectively. Therefore, the caller should be wary of waiting on this function. */ boolean isPerhapsHeld(); /** * This releases a lock, and cleans up any resources waiting on it. Calling this more than once is a no-op. */ CompletableFuture<Boolean> release(); /** {@inheritDoc} */ @Override default void close() throws Exception { release().get(); } } /** * The reason this is broken out from the interface is so that it is possible to mock LongLivedLock objects in the * RaftManagerMock. */ private class LongLivedLockImpl implements LongLivedLock { /** The name of the lock */ public final String lockName; /** A unique hash for this lock, to disambiguate this instance from other lock request instances of the same name. */ public final String uniqueHash; /** The window after which we should release the lock no matter what, as a last ditch on deadlocks. */ public final Duration safetyReleaseWindow; /** If true, we currently hold this lock. This is an optimistic boolean -- we may no longer hold it technically. */ private boolean held = true; /** If true, we want to hold this lock. If false, we are in the process of releasing it. */ private boolean wantToHold = true; public final SafeTimerTask cleanupTimerTask; /** * This creates a LongLivedLock object which will automatically clean itself up in the event of catastrophic * failure. * * @param lockName the name of the lock * @param uniqueHash the unique hash of the lock, to prevent the same machine from getting the same lock multiple * times. * @param safetyReleaseWindow a duration after which we will automatically release the lock, if it hasn't been * released by some other safety mechanism. */ protected LongLivedLockImpl(String lockName, String uniqueHash, Duration safetyReleaseWindow) { this.lockName = lockName; this.uniqueHash = uniqueHash; this.safetyReleaseWindow = safetyReleaseWindow; cleanupTimerTask = new LockCleanupTimerTask(this); node.transport.schedule(cleanupTimerTask, safetyReleaseWindow.toMillis()); } /** * Returns the name of the lock that is held. */ @Override public String lockName() { return this.lockName; } /** {@inheritDoc} */ @Override public boolean isCertainlyHeld() { return this.held && this.wantToHold; } /** {@inheritDoc} */ @Override public boolean isPerhapsHeld() { if (!this.held) { return false; } else if (this.wantToHold) { return true; } else { // This is the case where we may hold the lock, but don't want to. // Let's check the state machine for our lock, though this is a bit slow KeyValueStateMachine.QueueLock lock = stateMachine.locks.get(this.lockName); if (lock == null || !lock.holder.isPresent()) { // Case: there is no lock anymore synchronized (this) { this.held = false; } } else { // Case: someone else holds the lock KeyValueStateMachine.LockRequest holder = lock.holder.get(); synchronized (this) { this.held = holder.server.equals(serverName) && holder.uniqueHash.equals(this.uniqueHash); } } return this.held; } } /** * This releases a lock, and cleans up any resources waiting on it. Calling this more than once is a no-op. */ @Override public synchronized CompletableFuture<Boolean> release() { if (!wantToHold) { if (held) { log.warn("Double-releasing a lock will have no effect. We see that this lock is currently perhaps held; the only recourse is to wait for the failsafe to release the lock."); } return CompletableFuture.completedFuture(!held); } this.wantToHold = false; cleanupTimerTask.cancel(); byte[] transition = KeyValueStateMachine.createReleaseLockTransition(lockName, serverName, uniqueHash); return node.submitTransition(transition) // note[gabor]: don't retry; let the cleanup thread take care of it on // its own time. This is to prevent cascading release lock requests // queuing up. .whenComplete((success, e) -> { // note[gabor]: this is not exception-proof; `e` may not be null. handleReleaseLockResult(success, e, transition); }); } /** * This is a safety check to ensure that if a lock gets GC'd, it also gets released */ @SuppressWarnings("deprecation") // Note[gabor]: Yes, we're doing a bad thing, but it's better than the alternative... @Override protected void finalize() throws Throwable { try { super.finalize(); } finally { // Optimization: Don't take the synchronized block from within finalize unless we haven't released yet if (held) { log.warn("{} - LongLivedLock for \"{}\" is being cleaned up from finalize()! This is very bad!", serverName, lockName); synchronized (unreleasedLocks) { queueFailedLock(KeyValueStateMachine.createReleaseLockTransition(lockName, serverName, uniqueHash)); } synchronized (this) { // Check again inside the synchronized block for if we've released yet if (held) { release(); } } } } } } /** * This is a little hack of a class to let up have a TimerTask that keeps a weak reference to our LongLivedLock, so * that we can rely on the GC as a line of defense despite having the TimerTask outstanding. */ private static class LockCleanupTimerTask extends SafeTimerTask { /** The weak reference to our lock */ WeakReference<LongLivedLock> weakLock; public LockCleanupTimerTask(LongLivedLock longLivedLock) { weakLock = new WeakReference<>(longLivedLock); } @Override public void runUnsafe() { final LongLivedLock lock = weakLock.get(); // This has already been GC'd, so it's no problem if (lock == null) { return; } // Optimization: Don't take the synchronized block from within finalize unless we haven't released yet if (lock.isCertainlyHeld()) { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (lock) { // Check again inside the synchronized block for if we've released yet if (lock.isCertainlyHeld()) { log.warn("LongLivedLock for \"{}\" is being cleaned up from a TimerTask! This is very, very bad! It means we didn't release it, and finalize() never fired.", lock.lockName()); lock.release(); } } } } } /** * The name of our node. * This can also be gotten from {@link #node}.{@link EloquentRaftNode#algorithm}.{@link EloquentRaftAlgorithm#state}.{@link RaftState#serverName}. * But, from reading that path, you can tell why there's a helper here. */ public final String serverName; /** * The actual Raft node. This encapuslates a Raft algorithm with a transport. */ public final EloquentRaftNode node; /** * The state machine we're running over Raft. */ final KeyValueStateMachine stateMachine; /** * The RaftLifecycle that governs this Theseus */ public final RaftLifecycle lifecycle; /** * A set of release lock transitions that did not complete in their usual loop -- we should continue to * try to release these locks so long as we can, in hopes Raft comes back up sometime. */ // note[gabor]: Package protected to allow for fine-grained testing of the release locks thread final List<byte[]> unreleasedLocks = new ArrayList<>(); /** * If false, we have stopped this Raft. */ private boolean alive = true; /** * An executor pool for async tasks. */ private final ExecutorService pool; /** * The default timeout for our calls. Large enough that we can weather an election timeout, but small * enough that we we return a failure in a reasonable amount of time. */ private final Duration defaultTimeout; /** * The constructor takes three arguments: a cluster name (for discovery), a server name (for identifying ourselves, * must be unique within the cluster), and a reference to the lifecycle object that governs this Theseus (so that * tests can pass different RaftLifecycle objects to different Raft instances). * * @param algo The Raft algorithm to use. Defaults to {@link EloquentRaftAlgorithm}. * @param transport The type of transport to use for this Raft cluster. * @param lifecycle The governing RaftLifecycle for this Theseus, so that we can pass mock ones in inside tests */ public Theseus(RaftAlgorithm algo, RaftTransport transport, RaftLifecycle lifecycle) { // // I. Set variables // this.serverName = algo.serverName(); this.node = new EloquentRaftNode(algo, transport, lifecycle); this.node.registerShutdownHook(() -> { alive = false; // Wake up the lock cleanup thread synchronized (unreleasedLocks) { unreleasedLocks.notifyAll(); } }); this.defaultTimeout = Duration.ofMillis(node.algorithm.electionTimeoutMillisRange().end * 2); this.stateMachine = (KeyValueStateMachine) algo.mutableStateMachine(); this.lifecycle = lifecycle; this.pool = lifecycle.managedThreadPool("eloquent-raft-async", true); // // II. Create lock cleanup thread // Thread lockCleanupThread = new Thread(() -> { while (alive) { try { // 1. Wait on new unreleased locks byte[][] unreleasedLocksCopy; synchronized (unreleasedLocks) { while (unreleasedLocks.isEmpty() && alive) { try { unreleasedLocks.wait(node.algorithm.electionTimeoutMillisRange().end * 2); // allow any outstanding election to finish } catch (InterruptedException ignored) {} } unreleasedLocksCopy = unreleasedLocks.toArray(new byte[0][]); } if (unreleasedLocksCopy.length > 0 && // note[gabor]: only run if we have something to run (!alive || this.errors().isEmpty()) && // note[gabor]: only run if we're error free (or shutting down). Otherwise this is a foolish attempt this.node.algorithm.mutableState().leader.isPresent() // note[gabor]: if we have no leader (we're in the middle of an election), we're just asking for pain/ ) { // 2. Release the locks log.warn("Trying to release {} unreleased locks", unreleasedLocksCopy.length); byte[] bulkTransition = KeyValueStateMachine.createGroupedTransition(unreleasedLocksCopy); Boolean success = node.submitTransition(bulkTransition) .get(node.algorithm.electionTimeoutMillisRange().end + 100, TimeUnit.MILLISECONDS); if (success != null && success) { // 3.A. Success: stop trying locks log.warn("Successfully released {} unreleased locks", unreleasedLocksCopy.length); synchronized (unreleasedLocks) { unreleasedLocks.removeAll(Arrays.asList(unreleasedLocksCopy)); } } else { // 3.B. Failure: signal failure log.warn("Could not release {} locks; retrying later.", unreleasedLocksCopy.length); } } } catch (Throwable t) { if (t instanceof TimeoutException || (t instanceof CompletionException && t.getCause() != null && t.getCause() instanceof TimeoutException)) { log.info("Caught a timeout exception in the lockCleanupThread in Theseus"); } else { log.warn("Caught an exception in the lockCleanupThread in Theseus", t); } } } }); lockCleanupThread.setName("raft-lock-cleanup"); lockCleanupThread.setDaemon(true); lockCleanupThread.setPriority(Thread.MIN_PRIORITY); lockCleanupThread.start(); } /** * Create a new auto-resizing raft with the default algorithm, using the given transport. * * @param serverName The name of this server in the cluster. * @param transport The transport to use to communicate with the cluster. * @param targetClusterSize The target quorum size we try to maintain with auto-resizing * @param lifecycle The governing RaftLifecycle for this Theseus, so that we can pass mock ones in inside tests */ public Theseus(String serverName, RaftTransport transport, int targetClusterSize, RaftLifecycle lifecycle) { this( new SingleThreadedRaftAlgorithm( new EloquentRaftAlgorithm( serverName, new KeyValueStateMachine(serverName), transport, targetClusterSize, lifecycle.managedThreadPool("raft-public", true), Optional.of(lifecycle)), lifecycle.managedThreadPool("raft-pubic", true)), transport, lifecycle); } /** * Create a new fixed-size raft with the default algorithm, using the given transport. * * @param serverName The name of this server in the cluster. * @param initialMembership The initial cluster membership. * @param lifecycle The governing EloquentLifecycle for this Theseus, so that we can pass mock ones in inside tests */ public Theseus(String serverName, RaftTransport transport, Collection<String> initialMembership, RaftLifecycle lifecycle) { this( new SingleThreadedRaftAlgorithm( new EloquentRaftAlgorithm( serverName, new KeyValueStateMachine(serverName), transport, initialMembership, lifecycle.managedThreadPool("raft-public", true), Optional.of(lifecycle)), lifecycle.managedThreadPool("raft-pubic", true)), transport, lifecycle); } /** * Create a Raft cluster with a fixed quorum. * * @param serverName The server name for this Raft node. * @param quorum The fixed quorum for the cluster. * This is a set of server names * * @throws IOException Thrown if we could not create the underlying transport. */ public Theseus(String serverName, Collection<String> quorum) throws IOException { this( serverName, RaftTransport.create(serverName, RaftTransport.Type.NET), quorum, RaftLifecycle.global); } /** * Create a new dynamically resizing Raft cluster, with the given number * of nodes as the target quorum size. We will shrink the cluster if we have more * than this number, and grow it if we have less. * * @param targetQuorumSize The target number of nodes in the * quorum. * * @throws IOException Thrown if we could not create the underlying transport. */ public Theseus(int targetQuorumSize) throws IOException { this( defaultServerName.get(), RaftTransport.create(defaultServerName.get(), RaftTransport.Type.NET), targetQuorumSize, RaftLifecycle.global); } /** * The default name for this server, assuming only one Raft is running * per box (i.e., IP address) */ private static Lazy<String> defaultServerName = Lazy.of( () -> { // 1. Get the server name // 1.1. Get the host name, so that we're human readable String serverNameBuilder; try { serverNameBuilder = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { log.warn("Could not get InetAddress.getLocalHost() in order to determine Theseus' hostname", e); Optional<String> hostname = Optional.ofNullable(System.getenv("HOST")); serverNameBuilder = hostname.orElseGet(() -> UUID.randomUUID().toString()); } if (serverNameBuilder.contains("/")) { serverNameBuilder = serverNameBuilder.substring(serverNameBuilder.indexOf('/') + 1); } // 1.1. Append a random ID to avoid conflicts serverNameBuilder += "_" + System.currentTimeMillis(); return serverNameBuilder; } ); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Public interface: // // These are the methods that are safe to use with Raft, wrapped in an interface to avoid mistakes like forgetting to // release locks. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Stop this raft node. * */ public void close() { // Close the cluster node.close(); } /** * Start this Raft. * * @see EloquentRaftNode#start() */ void start() { node.start(); } /** * Bootstrap this cluster, if there are no leaders. * * @param force If true, attempt to take leadership by force. * That is, massively increase the term number. * * @return True if the cluster was successfully bootstrapped */ public boolean bootstrap(boolean force) { log.info("Bootstrapping Raft"); return node.bootstrap(force); } /** * Bootstrap this cluster, if there are no leaders. * * @return True if the cluster was successfully bootstrapped */ public boolean bootstrap() { return bootstrap(false); } /** * Get the current Raft state. Note that this is a copy -- it may not be up to date, * but it's safe to change */ public RaftState state() { return node.algorithm.state(); } /** * Return any errors Raft has encountered. */ public List<String> errors() { return node.errors(); } ////////////////////////////////////////////////////////////////// // With distributed locks ////////////////////////////////////////////////////////////////// /** @see #withDistributedLockAsync(String, Supplier) * * This wraps a runnable with an instantly complete future. */ public CompletableFuture<Boolean> withDistributedLockAsync(String lockName, Runnable runnable) { return withDistributedLockAsync(lockName, () -> CompletableFuture.supplyAsync(() -> { try { runnable.run(); return true; } catch (Throwable t) { log.warn("Caught exception on withDistributedLockAsync ", t); return false; } }, pool) ); } /** * This runs a function while holding a distributed lock. The lock is global across the cluster, so you're safe to run * from anywhere without fear of contention. This is similar to taking a SQL lock, but is much faster and is therefore * appropriate for much lower latency scenarios. * * @param lockName the name of the lock -- in a global flat namespace * @param runnable the runnable to execute while holding the lock */ public CompletableFuture<Boolean> withDistributedLockAsync(String lockName, Supplier<CompletableFuture<Boolean>> runnable) { // 1. Create and submit the lock request final String randomHash = UUID.randomUUID().toString(); byte[] releaseLockTransition = KeyValueStateMachine.createReleaseLockTransition(lockName, serverName, randomHash); return retryTransitionAsync(KeyValueStateMachine.createRequestLockTransition(lockName, serverName, randomHash), defaultTimeout).thenCompose((success) -> { // 2.a. If we fail to submit the transition to get the lock, it is possible that we failed while waiting for the // transition to commit, but the transition is still out there. To be totally correct, we need to release the lock // here in the rare event that the request lock transition is still around and eventually gets committed. if (!success) { return node.submitTransition(releaseLockTransition) // note[gabor]: let failsafe retry -- same reasoning as above. .whenComplete((s, e) -> { // note[gabor]: this is not exception-proof; `e` may not be null. handleReleaseLockResult(s, e, releaseLockTransition); }); } else { // 2.b. Otherwise, wait on the lock return stateMachine.createLockAcquiredFuture(lockName, serverName, randomHash).thenCompose((gotLock) -> { if (gotLock) { // 3. Run our runnable, which returns a CompletableFuture try { return runnable.get(); } catch (Throwable t) { log.warn("Uncaught exception on runnable in withDistributedLockAsync: ", t); return CompletableFuture.completedFuture(false); } } else { return CompletableFuture.completedFuture(false); } }).whenComplete((runSuccess, t) -> { // 4. Always release the lock node.submitTransition(releaseLockTransition) // note[gabor]: let failsafe retry -- same reasoning as above. .whenComplete((s, e) -> { // note[gabor]: this is not exception-proof; `e` may not be null. handleReleaseLockResult(s, e, releaseLockTransition); }); }); } }); } ////////////////////////////////////////////////////////////////// // Try locks ////////////////////////////////////////////////////////////////// /** * This will try to acquire a lock. It will block for network IO, but will not block waiting for the lock if the lock * is not immediately acquired upon request. It returns a LongLivedLock object that is a reference to this lock, and * contains a method to release it. The LongLivedLock object will also do its best to recover from situations where * users fail/forget to release the lock, though it will yell at you if it has to clean up after you. * * @param lockName the name of the lock to attempt to acquire * @param safetyReleaseWindow this is the duration of time after which we will automatically release the lock if it * hasn't already been released. This is just a safety check, you should set it to much * longer than you expect to hold the lock for. * @return if successful, a LongLivedLock object that can be kept around as a reference to this lock, with a method to * release it. If we were unable to acquire the lock, returns empty. */ public Optional<LongLivedLock> tryLock(String lockName, Duration safetyReleaseWindow) { try { return tryLockAsync(lockName, safetyReleaseWindow).get(); } catch (InterruptedException | ExecutionException e) { return Optional.empty(); } } /** * This will try to acquire a lock. It will block for network IO, but will not block waiting for the lock if the lock * is not immediately acquired upon request. It returns a LongLivedLock object that is a reference to this lock, and * contains a method to release it. The LongLivedLock object will also do its best to recover from situations where * users fail/forget to release the lock, though it will yell at you if it has to clean up after you. * * @param lockName the name of the lock to attempt to acquire * @param safetyReleaseWindow this is the duration of time after which we will automatically release the lock if it * hasn't already been released. This is just a safety check, you should set it to much * longer than you expect to hold the lock for. * @return if successful, a LongLivedLock object that can be kept around as a reference to this lock, with a method to * release it. If we were unable to acquire the lock, returns empty. */ public CompletableFuture<Optional<LongLivedLock>> tryLockAsync(String lockName, Duration safetyReleaseWindow) { String randomHash = Long.toHexString(new Random().nextLong()); CompletableFuture<Optional<LongLivedLock>> future = new CompletableFuture<>(); // 1. Create and submit the lock request retryTransitionAsync(KeyValueStateMachine.createTryLockTransition(lockName, serverName, randomHash), defaultTimeout).thenAccept((success) -> { try { // 2. If we got the lock, then return an object representing that if (stateMachine.locks.containsKey(lockName) && stateMachine.locks.get(lockName).holder.map(h -> h.server.equals(serverName) && h.uniqueHash.equals(randomHash)).orElse(false)) { future.complete(Optional.of(new LongLivedLockImpl(lockName, randomHash, safetyReleaseWindow))); } else { future.complete(Optional.empty()); } } catch (Throwable t) { // If something goes wrong, ensure we try to release the lock byte[] releaseLockTransition = KeyValueStateMachine.createReleaseLockTransition(lockName, serverName, randomHash); node.submitTransition(releaseLockTransition) // note[gabor]: let failsafe retry -- same reasoning as above. .whenComplete((s, e) -> { // note[gabor]: this is not exception-proof; `e` may not be null. handleReleaseLockResult(s, e, releaseLockTransition); future.complete(Optional.empty()); // wait for release to finish (or at least try to finish) to return }); } }); return future; } /** * Release a Raft lock * * @param lockName The name of the lock we are releasing * * @return A completable future for whether the lock was released */ public CompletableFuture<Boolean> releaseLock(String lockName) { KeyValueStateMachine.QueueLock lock = stateMachine.locks.get(lockName); if (lock != null && lock.holder.isPresent()) { KeyValueStateMachine.LockRequest holder = lock.holder.get(); return retryTransitionAsync(KeyValueStateMachine.createReleaseLockTransition(lockName, holder.server, holder.uniqueHash), defaultTimeout); } else { return CompletableFuture.completedFuture(false); } } ////////////////////////////////////////////////////////////////// // With element calls ////////////////////////////////////////////////////////////////// /** * Queue a failed lock release request. * The main point of this function, rather than just calling {@linkplain ArrayList#add(Object) add()} * on the underlying map, is to deduplicate lock release requests. * If a request is already queued, we don't double-add it. * * @param releaseLockTransition The request to queue. */ // note[gabor] package protected to allow fine-grained testing void queueFailedLock(byte[] releaseLockTransition) { synchronized (unreleasedLocks) { if (unreleasedLocks.size() < (0x1<<20)) { // 1M locks log.warn("Could not release lock! Queueing for later deletion."); boolean isDuplicate = false; for (byte[] lock : unreleasedLocks) { if (Arrays.equals(lock, releaseLockTransition)) { isDuplicate = true; break; } } if (!isDuplicate) { unreleasedLocks.add(releaseLockTransition); } } else { log.error("Could not release a lock and did not queue it for later deletion (queue full)"); } } } /** * This is a little helper that's responsible for queueing up a release lock transition, if necessary */ private void handleReleaseLockResult(Boolean success, Throwable error, byte[] releaseLockTransition) { if (error != null || success == null || !success) { // note[gabor] pass the boolean as an object to prevent possible null pointer if (error != null && !(error instanceof TimeoutException) && !(error instanceof CompletionException && error.getCause() != null && error.getCause() instanceof TimeoutException)) { log.warn("Release lock encountered an unexpected error: ", error); } queueFailedLock(releaseLockTransition); } } /** * This is the safest way to do a withElement() update. We take a global lock, and then manipulate the item, and set * the result. This means the mutator() can have side effects and not be idempotent, since it will only be called * once. This safety comes at a performance cost, since this requires two writes to the raft cluster. This is in * contrast to withElementIdempotent(), which uses a single compare-and-swap instead, to make it faster. * * Since we don't trust the Java serializer, which is used by Atomix for everything, we use a byte[] interface when * interacting with the distributed storage. That way we can store elements that have a proto serialization interface, * and still use proto. * * @param elementName the name of the element -- in a global flat namespace * @param mutator the function to call, while holding a lock on the element, to mutate the element (doesn't have to * actually change anything, but can). * @param createNew a function to supply a new element, if none is present in the map already * @param permanent if false, this element will be automatically removed when we disconnect from the cluster, if we're * the last people to have edited the element. * * @throws NoSuchElementException if we didn't supply a creator, and the object does not exist in Raft. * * @return true on success, false if something went wrong */ public CompletableFuture<Boolean> withElementAsync(String elementName, Function<byte[], byte[]> mutator, @Nullable Supplier<byte[]> createNew, boolean permanent) { // 1. Create the lock request // 1.1. The lock request final String randomHash = UUID.randomUUID().toString(); byte[] requestLockTransition = KeyValueStateMachine.createRequestLockTransition(elementName, serverName, randomHash); byte[] releaseLockTransition = KeyValueStateMachine.createReleaseLockTransition(elementName, serverName, randomHash); // 1.2. The lock release thunk Supplier<CompletableFuture<Boolean>> releaseLockWithoutChange = () -> node.submitTransition(releaseLockTransition) // note[gabor]: let failsafe retry -- same reasoning as above. .whenComplete((s, e) -> { // note[gabor]: this is not exception-proof; `e` may not be null. handleReleaseLockResult(s, e, releaseLockTransition); }); // 2. Submit the lock request return exceptionProof(retryTransitionAsync(requestLockTransition, defaultTimeout)).thenCompose((success) -> { // 3. Handle mutation now that lock is held // 3.a. If we fail to submit the transition to get the lock, it is possible that we failed while waiting for the // transition to commit, but the transition is still out there. To be totally correct, we need to release the lock // here in the rare event that the request lock transition is still around and eventually gets committed. if (!success) { return releaseLockWithoutChange.get(); } else { // 3.b. Otherwise, wait on the lock return stateMachine.createLockAcquiredFuture(elementName, serverName, randomHash).thenCompose((gotLock) -> { if (gotLock) { // Run our runnable, which returns a CompletableFuture try { // i. Get the object, if it is present Optional<byte[]> optionalObject = stateMachine.get(elementName, node.transport.now()); CompletableFuture<Boolean> future = new CompletableFuture<>(); pool.execute(() -> { // ii. Create the object, if it isn't present boolean newObject = false; byte[] object; if (optionalObject.isPresent()) { object = optionalObject.get(); } else if (createNew != null) { try { object = createNew.get(); newObject = true; } catch (Throwable e) { log.warn("withElementAsync() object creator threw an exception. Returning failure"); releaseLockWithoutChange.get().thenAccept(future::complete); return; } } else { log.warn("withElementAsync() object creator is null and there's nothing in the map. Returning failure"); releaseLockWithoutChange.get().thenAccept(future::complete); return; } // iii. If we returned a null from creation, that's a signal to stop the withElement call if (object == null) { releaseLockWithoutChange.get().thenAccept(future::complete); return; } // iv. Mutate the object byte[] mutated; try { mutated = mutator.apply(object); } catch (Throwable t) { releaseLockWithoutChange.get().thenAccept(future::complete); return; } // v. Put the object back into the map AND release the lock in a single transition if (newObject || (mutated != null && !Arrays.equals(object, mutated))) { // only if there was a change, or if it's a new object retryTransitionAsync( KeyValueStateMachine.createGroupedTransition(createSetValueTransition(elementName, mutated, permanent), releaseLockTransition), defaultTimeout).whenComplete((result, exception) -> { if (result == null || !result) { log.warn("Could not apply transition and/or release object lock: ", exception); releaseLockWithoutChange.get().thenAccept(future::complete); } else { future.complete(true); // SUCCESSFUL CASE } }); } else { // vi. If the mutator chose not to mutate the object, then this is trivially successful releaseLockWithoutChange.get().thenAccept(future::complete); } }); return future; } catch (Throwable t) { log.warn("Uncaught exception when mutating element in withElementAsync: ", t); return releaseLockWithoutChange.get(); } } else { // Always release the lock just in case return releaseLockWithoutChange.get(); } }); } }); } /** * Like {@link #withElementAsync(String, Function, Supplier, boolean)}, but without the safety of taking the lock on the element beforehand. * This is a bit of a dangerous method, as it can open the caller up to race conditions, and should be used sparingly. * * @param elementName the name of the element -- in a global flat namespace * @param mutator the function to call, while holding a lock on the element, to mutate the element (doesn't have to * actually change anything, but can). * @param createNew a function to supply a new element, if none is present in the map already * @param permanent if false, this element will be automatically removed when we disconnect from the cluster, if we're * the last people to have edited the element. * * @throws NoSuchElementException if we didn't supply a creator, and the object does not exist in Raft. * * @return true on success, false if something went wrong */ public CompletableFuture<Boolean> withElementUnlockedAsync(String elementName, Function<byte[], byte[]> mutator, @Nullable Supplier<byte[]> createNew, boolean permanent) { // 1. Get the object, if it is present Optional<byte[]> optionalObject = stateMachine.get(elementName, node.transport.now()); CompletableFuture<Boolean> future = new CompletableFuture<>(); pool.execute(() -> { // 2. Create the object, if it isn't present boolean newObject = false; byte[] object; if (optionalObject.isPresent()) { object = optionalObject.get(); } else if (createNew != null) { try { object = createNew.get(); newObject = true; } catch (Throwable e) { log.warn("withElementAsync() object creator threw an exception. Returning failure"); future.complete(false); return; } } else { log.warn("withElementAsync() object creator is null and there's nothing in the map. Returning failure"); future.complete(false); return; } // If we returned a null from creation, that's a signal to stop the withElement call if (object == null) { future.complete(false); return; } // 3. Mutate the object byte[] mutated = mutator.apply(object); // 4. Put the object back into the map if (newObject || (mutated != null && !Arrays.equals(object, mutated))) { // only if there was a change, or if it's a new object retryTransitionAsync(createSetValueTransition(elementName, mutated, permanent), defaultTimeout).whenComplete((success, t) -> { if (t != null) { future.completeExceptionally(t); } else { future.complete(success); } }); } else { // If the mutator chose not to mutate the object, then this is trivially successful future.complete(true); } }); return future; } ////////////////////////////////////////////////////////////////// // Set element calls ////////////////////////////////////////////////////////////////// /** * THIS IS DANGEROUS TO USE! People can clobber each other's writes, and there are tons of race conditions if you use * this call in conjunction with getElement() with no outside synchronization mechanism. Much safer, if you haven't * thought about it much, is to use withElement(). Only use setElement() if you're really certain that you are the * only one in the cluster writing, or you don't mind being clobbered. * * @param elementName the name of the element to write * @param value the value to set the element to * @param permanent if false, the element will be automatically removed when we disconnect from the cluster, if we're * the last people to have edited the element. If true, the element will stick around forever. */ @SuppressWarnings("unused") public CompletableFuture<Boolean> setElementAsync(String elementName, byte[] value, boolean permanent, Duration timeout) { return retryTransitionAsync(createSetValueTransition(elementName, value, permanent), timeout); } /** * Creates the right transition proto */ private byte[] createSetValueTransition(String elementName, byte[] value, boolean permanent) { if (permanent) { return KeyValueStateMachine.createSetValueTransition(elementName, value); } else { return KeyValueStateMachine.createSetValueTransitionWithOwner(elementName, value, serverName); } } ////////////////////////////////////////////////////////////////// // Remove element calls ////////////////////////////////////////////////////////////////// /** * This removes an element from the Raft key-value store. It's a no-op if the value isn't already in the database. * * @param elementName the name of the element to remove */ public CompletableFuture<Boolean> removeElementAsync(String elementName, Duration timeout) { // Remove the object from the map return retryTransitionAsync(KeyValueStateMachine.createRemoveValueTransition(elementName), timeout); } /** * This removes a set of elements from the Raft key-value store. It's a no-op if the value isn't already in the database. * * @param elementName the name of the element to remove */ public CompletableFuture<Boolean> removeElementsAsync(Set<String> elementName, Duration timeout) { // Create a grouped transition to remove all the elements from Raft at once return retryTransitionAsync(KeyValueStateMachine.createGroupedTransition(elementName.stream().map(KeyValueStateMachine::createRemoveValueTransition).collect(Collectors.toList()).toArray(new byte[elementName.size()][])), timeout); } ////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////// /** * This grabs the current state of an element, if it's present in the system. This may be out of date, since no lock * is held on the item when retrieving it. If a lock is desired then use withElement() instead. * * This is non-blocking and fast. * * @param elementName the name of the element -- in a global flat namespace */ public Optional<byte[]> getElement(String elementName) { return stateMachine.get(elementName, node.transport.now()); } /** * This returns the current understanding of the cluster membership on this node. */ public Set<String> getConfiguration() { return node.algorithm.mutableState().log.getQuorumMembers(); } /** * This returns a snapshot of the current values in the state machine. This is passed by value, not by reference, so * this is safe to hold on to. */ public Map<String, byte[]> getMap() { return stateMachine.map(); } /** * This returns the current keys in the state machine. It's impossible to hold some sort of lock while fetching these, * so these will be an eventually-consistent set, not an immediately consistent set. */ public Collection<String> getKeys() { return stateMachine.keys(); } /** * Get the set of locks that are held by the state machine, and the server that holds them. * The keys are locks, mapped to the server that holds it. */ public Map<String, String> getLocks() { Map<String, String> locks = new HashMap<>(); for (Map.Entry<String, KeyValueStateMachine.QueueLock> entry : stateMachine.locks.entrySet()) { locks.put(entry.getKey(), entry.getValue().holder.map(x -> x.server).orElse("<none>")); } return locks; } ////////////////////////////////////////////////////////////////// // Change listeners ////////////////////////////////////////////////////////////////// /** * This registers a listener that will be called whenever the key-value store changes. * * @param changeListener the listener to register */ public synchronized void addChangeListener(KeyValueStateMachine.ChangeListener changeListener) { stateMachine.addChangeListener(changeListener); } /** * This removes a listener that will be called whenever the key-value store changes. * * @param changeListener the listener to deregister */ public synchronized void removeChangeListener(KeyValueStateMachine.ChangeListener changeListener) { stateMachine.removeChangeListener(changeListener); } ////////////////////////////////////////////////////////////////// // Error listeners ////////////////////////////////////////////////////////////////// /** * Raft keeps track of an additional error listener * Errors are thrown from {@link KeyValueStateMachine} and {@link EloquentRaftNode} by default but * users are free to attach their own error listeners * * * Usage: * RaftErrorHandler errorListener = (debugMessage, stackTrace) -&gt; { * // Do something with the debug message / stackTrace * // Eg. Logging, or alerting via PagerDuty * } * addErrorListener(errorListener); * * // Later in the code where there is an error * throwRaftError(incident_key, debug_message); * * @param errorListener The error listener to add. */ public void addErrorListener(RaftErrorListener errorListener) { stateMachine.addErrorListener(errorListener); node.addErrorListener(errorListener); if (pool instanceof TrackedExecutorService) { ((TrackedExecutorService) pool).addErrorListener(errorListener); } } /** * Remove an error listener from Raft. * * @param errorListener The error listener to remove. */ @SuppressWarnings("unused") public void removeErrorListener(RaftErrorListener errorListener) { stateMachine.removeErrorListener(errorListener); node.removeErrorListener(errorListener); if (pool instanceof TrackedExecutorService) { ((TrackedExecutorService) pool).removeErrorListener(errorListener); } } /** * Remove all error listeners from Raft. */ @SuppressWarnings("unused") public void clearErrorListeners() { stateMachine.clearErrorListeners(); node.clearErrorListeners(); if (pool instanceof TrackedExecutorService) { ((TrackedExecutorService) pool).clearErrorListeners(); } } ////////////////////////////////////////////////////////////////// // Private implementation details ////////////////////////////////////////////////////////////////// /** * This returns a CompletableFuture for retrying a transition up until the timeout is reached. * * @param transition the transition we're trying to apply * @param timeout a length of time in which to retry failed transitions - IMPORTANT: the CompletableFuture returned * doesn't have to finish in this amount of time, we just stop retrying failed transitions after this * window elapses. * @return a CompletableFuture for the transition wrapped in retries */ private CompletableFuture<Boolean> retryTransitionAsync(byte[] transition, Duration timeout) { int uniqueID = new Random().nextInt(); long startTime = System.currentTimeMillis(); log.trace("\n-------------\nSTARTING TRANSITION {}\n-------------\n", uniqueID); return retryAsync(() -> node.submitTransition(transition), timeout).thenApply((success) -> { log.trace("\n-------------\nFINISHED TRANSITION {}: {} ({})\n-------------\n", uniqueID, success, TimerUtils.formatTimeSince(startTime)); return success; }); } /** * This is a helper that takes a CompletableFuture<Boolean> and wraps it so that it cannot return an exception, * instead it just returns false. * * @param future the future to wrap * @return a CompletableFuture that will never complete exceptionally */ private static CompletableFuture<Boolean> exceptionProof(CompletableFuture<Boolean> future) { CompletableFuture<Boolean> wrapper = new CompletableFuture<>(); future.whenComplete((success, t) -> { if (t != null) { if (t instanceof TimeoutException || (t instanceof CompletionException && t.getCause() != null && t.getCause() instanceof TimeoutException)) { log.info("Caught a timeout exception exception proof wrapper"); } else { log.warn("Caught an exception in exception proof wrapper", t); } wrapper.complete(false); } else { wrapper.complete(success); } }); return wrapper; } /** * This returns a CompletableFuture for retrying a transition up until the timeout is reached. * * @param action the action to retry, which returns a CompletableFuture indicating when the action is done and what * the status of the action was. * @param timeout a length of time in which to retry failed transitions - IMPORTANT: the CompletableFuture returned * doesn't have to finish in this amount of time, we just stop retrying failed transitions after this * window elapses. * @return a CompletableFuture for the transition wrapped in retries */ private CompletableFuture<Boolean> retryAsync(Supplier<CompletableFuture<Boolean>> action, Duration timeout) { long startTime = node.transport.now(); // Create a transition future CompletableFuture<Boolean> future = exceptionProof(action.get()); return future.thenCompose((result) -> { if (result) { // A. Case: the future was successful return CompletableFuture.completedFuture(true); } else { log.warn("Retrying a failed transition @ {} - this is fine, but should be rare", node.transport.now()); // B. Case: the future failed // B.1. Get the remaining time on the timeout long elapsed = node.transport.now() - startTime; long remainingTime = timeout.toMillis() - elapsed; // B.2. Check if there's still time on the timeout, and we haven't shut down the node yet if (remainingTime < 0 || !node.isAlive()) { return CompletableFuture.completedFuture(false); } // B.3. Retry if there's still time CompletableFuture<Boolean> ret = new CompletableFuture<>(); node.transport.schedule(new SafeTimerTask() { @Override public void runUnsafe() { retryAsync(action, Duration.ofMillis(remainingTime)).thenApply(ret::complete); } }, node.algorithm.electionTimeoutMillisRange().begin / 5); // Wait a bit before trying again, to avoid flooding the system with too many requests return ret; } }); } /** * If true, this node is the leader of the Raft cluster. */ public boolean isLeader() { return node.algorithm.mutableState().isLeader(); } /** * Register a new failsafe to run occasionally on this raft node. * * @param failsafe the one to register */ public void registerFailsafe(RaftFailsafe failsafe) { node.registerFailsafe(failsafe); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/UnsatisfiableQuorumFailsafe.java
package ai.eloquent.raft; import ai.eloquent.data.UDPTransport; import ai.eloquent.util.IOSupplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetAddress; import java.time.Duration; import java.util.Collections; /** * This failsafe checks for the following very specific condition: * * - 1. We believe we're the leader * - 2. There are other members in our cluster config * - 3. It has been more than 30 seconds since we got messages from any other cluster member * - 4. We can confirm with Kubernetes that none of the other cluster members we think we have are still alive * * In that case, we go ahead and commit the change to the cluster that all the other cluster members are dead, so we * can proceed. */ public class UnsatisfiableQuorumFailsafe implements RaftFailsafe { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(UnsatisfiableQuorumFailsafe.class); /** * The method for getting our ground truth cluster state. */ private final IOSupplier<String[]> getClusterState; /** * The timeout, in milliseconds, after which the failsafe should trigger. * A sensible default if you're using {@link EloquentRaftAlgorithm} is * {@link EloquentRaftAlgorithm#MACHINE_DOWN_TIMEOUT} + 15s */ public final long timeout; /** * Create a new failsafe from the default Kubernetes state in {@link UDPTransport#readKubernetesState()}. */ public UnsatisfiableQuorumFailsafe(Duration timeout) { this(() -> { InetAddress[] addresses = UDPTransport.readKubernetesState(); String[] names = new String[addresses.length]; for (int i = 0; i < addresses.length; i++) { names[i] = addresses[i].getHostAddress(); } return names; }, timeout); } /** * Create a new failsafe from the given cluster state provider. */ public UnsatisfiableQuorumFailsafe(IOSupplier<String[]> getClusterState, Duration timeout) { this.getClusterState = getClusterState; this.timeout = timeout.toMillis(); } /** {@inheritDoc} */ @Override public void heartbeat(RaftAlgorithm algorithm, long now) { RaftState state = algorithm.mutableState(); // 1. We believe we're the leader (or a candidate to become one) if (state.isLeader()) { state.lastMessageTimestamp.ifPresent(lastMessageTimestamp -> { // 2. There are other members in our cluster config if (lastMessageTimestamp.isEmpty()) { return; } // 3. It has been too long since we got messages from any other cluster member for (String member : lastMessageTimestamp.keySet()) { long timeSinceHeard = now - lastMessageTimestamp.get(member); if (timeSinceHeard <= this.timeout) { return; } } // 4. We can confirm with Kubernetes that none of the other cluster members we think we have are still alive try { String[] cluster = this.getClusterState.get(); for (String member : lastMessageTimestamp.keySet()) { if (!member.equalsIgnoreCase(algorithm.serverName())) { for (String hostname : cluster) { if (member.equals(hostname)) { return; } } } } } catch (IOException e) { log.warn("Could not get Kubernetes state -- ignoring failsafe! ", e); return; // don't reconfigure on Kubernetes glitches } // 5. If we reach here, we're in need of triggering the failsafe log.warn("UNSATISFIABLE QUORUM FAILSAFE TRIGGERED! This means we detected a deadlock or split brain in Raft, where all the other " + "boxes that are part of the cluster are now dead. This is obviously bad, and should never happen. We're now " + "going to attempt to recover automatically, but the root cause should be investigated (probably that boxes are " + "not respecting their shutdown locks). Good luck."); // 6. Immediately reconfigure to just us alone in a cluster state.reconfigure(Collections.singleton(algorithm.serverName()), true, now); }); } } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/raft/package-info.java
/** * Theseus: Eloquent's Raft implementation. */ package ai.eloquent.raft;
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/stats/IntCounter.java
package ai.eloquent.stats; import java.util.HashMap; import java.util.Map; import java.util.Set; public class IntCounter<E> { @SuppressWarnings({"NonSerializableFieldInSerializableClass"}) private Map<E, Integer> map; private int defaultValue = 0; // CONSTRUCTOR /** * Constructs a new (empty) Counter. */ public IntCounter() { map = new HashMap<>(); } /** * Adds 1 to the count for the given key. If the key hasn't been seen * before, it is assumed to have count 0, and thus this method will set * its count to 1. */ public double incrementCount(E key) { if (map.get(key) == null) { map.put(key, defaultValue); return 1; } else { int count = map.get(key) + 1; map.put(key, count); return count; } } public void setCount(E key, Integer value) { map.put(key, value); } public int totalIntCount() { return map.values() .stream() .mapToInt(Integer::intValue) .sum(); } public Set<Map.Entry<E, Integer>> entrySet() { return map.entrySet(); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/test/IntegrationTests.java
package ai.eloquent.test; /** * Mark a test as being slow and requiring external integrations (e.g., Rabbit). Usage: * * <pre>@Category(IntegrationTests.class)</pre> * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public interface IntegrationTests { }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/test/SlowTests.java
package ai.eloquent.test; /** * Mark a test as being a slow fuzz-test. * * <pre>@Category(SlowTests.class)</pre> * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public interface SlowTests { }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/ConcurrencyUtils.java
package ai.eloquent.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.Collection; import java.util.List; import java.util.concurrent.locks.ReentrantLock; /** * Static utilities for dealing with concurrency -- primarily, with * ensuring correctness. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class ConcurrencyUtils { /** * An SLF4J Logger for this class. */ @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(ConcurrencyUtils.class); /** * Thread info bean. */ private static ThreadMXBean threadmx = ManagementFactory.getThreadMXBean(); /** Static utility class */ private ConcurrencyUtils() {} /** * A helper for determining if we can take the given lock according to the lock order. * * @param lockOrder The lock order we are checking against. * @param lockBeingTaken The lock we are trying to take. This can either be a {@link ReentrantLock} or * an object we're synchronizing on. * * @return Throws an assert error if something goes wrong, but also returns false just in case. */ @SuppressWarnings({"Duplicates", "ConstantConditions"}) public static boolean ensureLockOrder(List<Object> lockOrder, Object lockBeingTaken) { // Check that there's a lock order defined if (lockOrder.isEmpty()) { return true; // we're safe } // Get the locks before the taken lock int lockIndex = lockOrder.indexOf(lockBeingTaken); assert lockIndex >= 0 && lockIndex < lockOrder.size() : "Could not find lock in lock order: " + lockBeingTaken; if (lockIndex < 0 || lockIndex >= lockOrder.size()) { return false; } // If we already hold the lock, and it's Reentrant, then this is fine if (lockBeingTaken instanceof ReentrantLock) { if (((ReentrantLock)lockBeingTaken).isHeldByCurrentThread()) { return true; } } // Check that the subsequent locks aren't taken for (int i = lockIndex + 1; i < lockOrder.size(); ++i) { Object downstreamLock = lockOrder.get(i); if (downstreamLock instanceof ReentrantLock) { assert !((ReentrantLock) downstreamLock).isHeldByCurrentThread() : "Trying to take lock " + lockBeingTaken + " (index " + lockIndex + ") but already hold later lock " + downstreamLock + " (index " + i + ")"; if (((ReentrantLock) downstreamLock).isHeldByCurrentThread()) { return false; } // (just in case we're synchronizing on a ReentrantLock) assert !Thread.holdsLock(downstreamLock) : "Trying to take lock " + lockBeingTaken + " (index " + lockIndex + " ) but already hold later lock " + downstreamLock + " (index " + i + ")"; if (Thread.holdsLock(downstreamLock)) { return false; } } else { assert !Thread.holdsLock(downstreamLock) : "Trying to take lock " + lockBeingTaken + " (index " + lockIndex + ") but already hold later lock " + downstreamLock + " (index " + i + ")"; if (Thread.holdsLock(downstreamLock)) { return false; } } } // OK, we can take the lock return true; } /** * Ensure that none of the given locks are being held by the current thread. * This is useful for, e.g., checking that we are not holding any locks on network calls. * * @param lockOrder The lock order. The order here doesn't matter, but is meant to * mirror {@link #ensureLockOrder(List, Object)}. * * @return Throws an assert error if something goes wrong, but also returns false just in case. */ public static boolean ensureNoLocksHeld(Collection<Object> lockOrder) { for (Object downstreamLock : lockOrder) { if (downstreamLock instanceof ReentrantLock) { assert !((ReentrantLock) downstreamLock).isHeldByCurrentThread() : "Lock " + downstreamLock + " is held by the current thread ( " + Thread.currentThread() + ")"; if (((ReentrantLock) downstreamLock).isHeldByCurrentThread()) { return false; } // (just in case we're synchronizing on a ReentrantLock) assert !Thread.holdsLock(downstreamLock) : "Lock " + downstreamLock + " is held by the current thread ( " + Thread.currentThread() + ")"; if (Thread.holdsLock(downstreamLock)) { return false; } } else { assert !Thread.holdsLock(downstreamLock) : "Lock " + downstreamLock + " is held by the current thread ( " + Thread.currentThread() + ")"; if (Thread.holdsLock(downstreamLock)) { return false; } } } return true; } /** * Ensure that the current thread does not hold any synchronized block locks. * Note that this method <b>cannot</b> check {@linkplain java.util.concurrent.locks.Lock explicit locks}. * * @return Throws an assert error if something goes wrong, but also returns false just in case. */ public static boolean ensureNoLocksHeld() { ThreadInfo threadInfo = threadmx.getThreadInfo(new long[]{Thread.currentThread().getId()}, true, false)[0]; LockInfo[] monitorsHeld = threadInfo.getLockedMonitors(); assert monitorsHeld.length == 0 : "Thread holds " + monitorsHeld.length + " monitor locks (first is " + monitorsHeld[0].getClassName() + ")"; LockInfo[] objThreadsHeld = threadInfo.getLockedSynchronizers(); // this is always empty unless lockedSynchronizers is set to true in the getThreadInfo() call assert objThreadsHeld.length == 0 : "Thread holds " + objThreadsHeld.length + " synchronizers (first is " + objThreadsHeld[0].getClassName() + ")"; // noinspection ConstantConditions // note[gabor]: Not always true if we don't have asserts on. return objThreadsHeld.length == 0 && monitorsHeld.length == 0; } /** * Ensure that <b>all</b> of the given locks are being held by the current thread. * This is useful for, e.g., checking that we hold a lock on a future * * @param lockOrder The lock order. The order here doesn't matter, but is meant to * mirror {@link #ensureLockOrder(List, Object)}. * * @return Throws an assert error if something goes wrong, but also returns false just in case. */ public static boolean ensureLocksHeld(Collection<Object> lockOrder) { if (lockOrder.isEmpty()) { return true; } for (Object downstreamLock : lockOrder) { if (downstreamLock instanceof ReentrantLock) { assert ((ReentrantLock) downstreamLock).isHeldByCurrentThread() : "Lock " + downstreamLock + " is not held by the current thread ( " + Thread.currentThread() + ")"; if (!((ReentrantLock) downstreamLock).isHeldByCurrentThread()) { return false; } // (just in case we're synchronizing on a ReentrantLock) assert Thread.holdsLock(downstreamLock) : "Lock " + downstreamLock + " is not held by the current thread ( " + Thread.currentThread() + ")"; if (!Thread.holdsLock(downstreamLock)) { return false; } } else { assert Thread.holdsLock(downstreamLock) : "Lock " + downstreamLock + " is not held by the current thread ( " + Thread.currentThread() + ")"; if (!Thread.holdsLock(downstreamLock)) { return false; } } } return true; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/FunctionalUtils.java
package ai.eloquent.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; /** * Utility functions for working with monads (e.g., Java's {@link Optional}) or * creating monad-style operations. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class FunctionalUtils { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(FunctionalUtils.class); /** * Return an empty concurrent map. * * @param <K> The key type of the map. * @param <V> The value type of the map. * * @return The map instance. */ public static <K, V> ConcurrentHashMap<K,V> emptyConcurrentMap() { return new ConcurrentHashMap<>(0); } public static <E> Optional<E> ofThrowable(ThrowableSupplier<E> elem, boolean printErrors) { E value = null; try { value = elem.get(); } catch (Throwable e) { if (printErrors) { log.warn("Exception in creating Optional: {}, {}", e.getClass().getSimpleName(), e.getMessage()); } } return Optional.ofNullable(value); } public static <E> Optional<E> ofThrowable(ThrowableSupplier<E> elem) { return ofThrowable(elem, false); } /** * Returns either a singleton stream of the value computed by the argument, or an empty stream. */ public static <E> Stream<E> streamOfThrowable(ThrowableSupplier<E> elem) { E value = null; try { value = elem.get(); } catch (Throwable ignored) { } if (value != null) { return Stream.of(value); } else { return Stream.empty(); } } /** * Like {@link Collections#unmodifiableMap(Map)}, but does not wrap already unmodifiable maps in the unmodifiable map class. * This avoids memory bloat and/or stack overflows for deep wrapping of immutable collections (e.g., if * a constructor makes something immutable). */ public static <E, F> Map<E, F> immutable(Map<E, F> map) { if (map instanceof AbstractMap) { return Collections.unmodifiableMap(map); } else { return map; } } /** * Like {@link Collections#unmodifiableList(List)}, but does not wrap already unmodifiable lists in the unmodifiable list class. * This avoids memory bloat and/or stack overflows for deep wrapping of immutable collections (e.g., if * a constructor makes something immutable). */ public static <E> List<E> immutable(List<E> lst) { if (lst instanceof AbstractList) { return Collections.unmodifiableList(lst); } else { return lst; } } /** * Like {@link Collections#unmodifiableSet(Set)}, but does not wrap already unmodifiable sets in the unmodifiable set class. * This avoids memory bloat and/or stack overflows for deep wrapping of immutable collections (e.g., if * a constructor makes something immutable). */ public static <E> Set<E> immutable(Set<E> set) { if (set instanceof AbstractSet) { return Collections.unmodifiableSet(set); } else { return set; } } /** * I can't believe this isn't in the Java standard library for flat mapping between streams and optionals. */ public static <E> Stream<E> streamFromOptional(Optional<E> opt) { return opt.map(Stream::of).orElseGet(Stream::empty); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/IOSupplier.java
package ai.eloquent.util; import java.io.IOException; import java.util.function.Supplier; /** * A supplier which can throw an IOexception. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ @FunctionalInterface public interface IOSupplier<E> { /** * @see Supplier#get() */ E get() throws IOException; }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/IdentityHashSet.java
package ai.eloquent.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.*; /** This class provides a <code>IdentityHashMap</code>-backed * implementation of the <code>Set</code> interface. This means that * whether an object is an element of the set depends on whether it is == * (rather than <code>equals()</code>) to an element of the set. This is * different from a normal <code>HashSet</code>, where set membership * depends on <code>equals()</code>, rather than ==. * * Each element in the set is a key in the backing IdentityHashMap; each key * maps to a static token, denoting that the key does, in fact, exist. * * Most operations are O(1), assuming no hash collisions. In the worst * case (where all hashes collide), operations are O(n). * * @author Bill MacCartney */ public class IdentityHashSet<E> extends AbstractSet<E> implements Cloneable, Serializable { // todo: The Java bug database notes that "From 1.6, an identity hash set can be created by Collections.newSetFromMap(new IdentityHashMap())." // INSTANCE VARIABLES ------------------------------------------------- // the IdentityHashMap which backs this set private transient IdentityHashMap<E,Boolean> map; private static final long serialVersionUID = -5024744406713321676L; // CONSTRUCTORS --------------------------------------------------------- /** Construct a new, empty IdentityHashSet whose backing IdentityHashMap * has the default expected maximum size (21); */ public IdentityHashSet() { map = new IdentityHashMap<>(); } /** Construct a new, empty IdentityHashSet whose backing IdentityHashMap * has the specified expected maximum size. Putting more than the * expected number of elements into the set may cause the internal data * structure to grow, which may be somewhat time-consuming. * * @param expectedMaxSize the expected maximum size of the set. */ public IdentityHashSet(int expectedMaxSize) { map = new IdentityHashMap<>(expectedMaxSize); } /** Construct a new IdentityHashSet with the same elements as the supplied * Collection (eliminating any duplicates, of course); the backing * IdentityHashMap will have the default expected maximum size (21). * * @param c a Collection containing the elements with which this set will * be initialized. */ public IdentityHashSet(Collection<? extends E> c) { map = new IdentityHashMap<>(); addAll(c); } // PUBLIC METHODS --------------------------------------------------------- /** Adds the specified element to this set if it is not already present. * * Remember that this set implementation uses == (not * <code>equals()</code>) to test whether an element is present in the * set. * * @param o element to add to this set * @return true if the element was added, * false otherwise */ @Override public boolean add(E o) { if (map.containsKey(o)) { return false; } else { internalAdd(o); return true; } } /** Removes all of the elements from this set. */ @Override public void clear() { map.clear(); } /** Returns a shallow copy of this <code>IdentityHashSet</code> instance: * the elements themselves are not cloned. * * @return a shallow copy of this set. */ @Override public Object clone() { Iterator<E> it = iterator(); IdentityHashSet<E> clone = new IdentityHashSet<>(size() * 2); while (it.hasNext()) { clone.internalAdd(it.next()); } return clone; } /** Returns true if this set contains the specified element. * * Remember that this set implementation uses == (not * <code>equals()</code>) to test whether an element is present in the * set. * * @param o Element whose presence in this set is to be * tested. * * @return <code>true</code> if this set contains the specified element. */ @Override public boolean contains(Object o) { return map.containsKey(o); } /** Returns <code>true</code> if this set contains no elements. * * @return <code>true</code> if this set contains no elements. */ @Override public boolean isEmpty() { return map.isEmpty(); } /** Returns an iterator over the elements in this set. The elements are * returned in no particular order. * * @return an <code>Iterator</code> over the elements in this set. */ @Override public Iterator<E> iterator() { return map.keySet().iterator(); } /** Removes the specified element from this set if it is present. * * Remember that this set implementation uses == (not * <code>equals()</code>) to test whether an element is present in the * set. * * @param o Object to be removed from this set, if present. * * @return <code>true</code> if the set contained the specified element. */ @Override public boolean remove(Object o) { return (map.remove(o) != null); } /** Returns the number of elements in this set (its cardinality). * * @return the number of elements in this set (its cardinality). */ @Override public int size() { return map.size(); } // PRIVATE METHODS ----------------------------------------------------------- /** Adds the supplied element to this set. This private method is used * internally [by clone()] instead of add(), because add() can be * overridden to do unexpected things. * * @param o the element to add to this set */ private void internalAdd(E o) { map.put(o, Boolean.TRUE); } /** Serialize this Object in a manner which is binary-compatible with the * JDK. */ private void writeObject(ObjectOutputStream s) throws IOException { Iterator<E> it = iterator(); s.writeInt(size() * 2); // expectedMaxSize s.writeInt(size()); while (it.hasNext()) s.writeObject(it.next()); } /** Deserialize this Object in a manner which is binary-compatible with * the JDK. */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { int size, expectedMaxSize; Object o; expectedMaxSize = s.readInt(); size = s.readInt(); map = new IdentityHashMap<>(expectedMaxSize); for (int i = 0; i < size; i++) { o = s.readObject(); internalAdd(uncheckedCast(o)); } } /** * Casts an Object to a T * @param <E> */ @SuppressWarnings("unchecked") public static <E> E uncheckedCast(Object o) { return (E) o; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/Lazy.java
package ai.eloquent.util; import java.lang.ref.SoftReference; import java.util.function.Supplier; /** * An instantiation of a lazy object. * * @author Gabor Angeli &lt;gabor@eloquent.ai&gt; */ public abstract class Lazy<E> { /** If this lazy should cache, this is the cached value. */ private SoftReference<E> implOrNullCache = null; /** If this lazy should not cache, this is the computed value */ private E implOrNull = null; /** For testing only: simulate a GC event. */ void simulateGC() { if (implOrNullCache != null) { implOrNullCache.clear(); } } /** * Get the value of this {@link Lazy}, computing it if necessary. */ public synchronized E get() { E orNull = getIfDefined(); if (orNull == null) { orNull = compute(); if (isCache()) { implOrNullCache = new SoftReference<>(orNull); } else { implOrNull = orNull; } } assert orNull != null; return orNull; } /** * Compute the value of this lazy. */ protected abstract E compute(); /** * Specify whether this lazy should garbage collect its value if needed, * or whether it should force it to be persistent. */ public abstract boolean isCache(); /** * Get the value of this {@link Lazy} if it's been initialized, or else * return null. */ public E getIfDefined() { if (implOrNullCache != null) { assert implOrNull == null; return implOrNullCache.get(); } else { return implOrNull; } } /** * Check if this lazy has been garbage collected, if it is a cached value. * Useful for, e.g., clearing keys in a map when the values are already gone. */ public boolean isGarbageCollected() { return this.isCache() && (this.implOrNullCache == null || this.implOrNullCache.get() == null); } /** * Create a degenerate {@link Lazy}, which simply returns the given pre-computed * value. */ public static <E> Lazy<E> from(final E definedElement) { Lazy<E> rtn = new Lazy<E>() { @Override protected E compute() { return definedElement; } @Override public boolean isCache() { return false; } }; rtn.implOrNull = definedElement; return rtn; } /** * Create a lazy value from the given provider. * The provider is only called once on initialization. */ public static <E> Lazy<E> of(Supplier<E> fn) { return new Lazy<E>() { @Override protected E compute() { return fn.get(); } @Override public boolean isCache() { return false; } }; } /** * Create a lazy value from the given provider, allowing the value * stored in the lazy to be garbage collected if necessary. * The value is then re-created by when needed again. */ public static <E> Lazy<E> cache(Supplier<E> fn) { return new Lazy<E>() { @Override protected E compute() { return fn.get(); } @Override public boolean isCache() { return true; } }; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/Pair.java
package ai.eloquent.util; import java.io.DataOutputStream; import java.util.List; /** * Pair is a Class for holding mutable pairs of objects. */ public class Pair <T1,T2> implements Comparable<Pair<T1,T2>> { /** * Direct access is deprecated. Use first(). * * @serial */ public T1 first; /** * Direct access is deprecated. Use second(). * * @serial */ public T2 second; public Pair() { // first = null; second = null; -- default initialization } public Pair(T1 first, T2 second) { this.first = first; this.second = second; } public T1 first() { return first; } public T2 second() { return second; } public void setFirst(T1 o) { first = o; } public void setSecond(T2 o) { second = o; } @Override public String toString() { return "(" + first + "," + second + ")"; } @Override public boolean equals(Object o) { if (o instanceof Pair) { @SuppressWarnings("rawtypes") Pair p = (Pair) o; return (first == null ? p.first() == null : first.equals(p.first())) && (second == null ? p.second() == null : second.equals(p.second())); } else { return false; } } @Override public int hashCode() { int firstHash = (first == null ? 0 : first.hashCode()); int secondHash = (second == null ? 0 : second.hashCode()); return firstHash*31 + secondHash; } /** * Returns a Pair constructed from X and Y. Convenience method; the * compiler will disambiguate the classes used for you so that you * don't have to write out potentially long class names. */ public static <X, Y> Pair<X, Y> makePair(X x, Y y) { return new Pair<>(x, y); } /** * Write a string representation of a Pair to a DataStream. * The <code>toString()</code> method is called on each of the pair * of objects and a <code>String</code> representation is written. * This might not allow one to recover the pair of objects unless they * are of type <code>String</code>. */ public void save(DataOutputStream out) { try { out.writeUTF(first.toString()); out.writeUTF(second.toString()); } catch (Exception e) { e.printStackTrace(); } } /** * Compares this <code>Pair</code> to another object. * If the object is a <code>Pair</code>, this function will work providing * the elements of the <code>Pair</code> are themselves comparable. * It will then return a value based on the pair of objects, where * <code>p &gt; q iff p.first() &gt; q.first() || * (p.first().equals(q.first()) &amp;&amp; p.second() &gt; q.second())</code>. * If the other object is not a <code>Pair</code>, it throws a * <code>ClassCastException</code>. * * @param another the <code>Object</code> to be compared. * @return the value <code>0</code> if the argument is a * <code>Pair</code> equal to this <code>Pair</code>; a value less than * <code>0</code> if the argument is a <code>Pair</code> * greater than this <code>Pair</code>; and a value * greater than <code>0</code> if the argument is a * <code>Pair</code> less than this <code>Pair</code>. * @throws ClassCastException if the argument is not a * <code>Pair</code>. * @see java.lang.Comparable */ @SuppressWarnings("unchecked") public int compareTo(Pair<T1,T2> another) { if (first() instanceof Comparable) { int comp = ((Comparable<T1>) first()).compareTo(another.first()); if (comp != 0) { return comp; } } if (second() instanceof Comparable) { return ((Comparable<T2>) second()).compareTo(another.second()); } if ((!(first() instanceof Comparable)) && (!(second() instanceof Comparable))) { throw new AssertionError("Neither element of pair comparable"); } return 0; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/Pointer.java
package ai.eloquent.util; import java.io.Serializable; import java.util.Optional; /** * A pointer to an object, to get around not being able to access non-final * variables within an anonymous function. * * @author Gabor Angeli */ public class Pointer<T> implements Serializable { /** The serial version uid to ensure stable serialization. */ private static final long serialVersionUID = 1L; /** * The value the pointer is set to, if it is set. */ private T impl; /** * Create a pointer pointing nowhere. */ public Pointer() { this.impl = null; } /** * Create a pointer pointing at the given object. * * @param impl The object the pointer is pointing at. */ public Pointer(T impl) { this.impl = impl; } /** * Dereference the pointer. * If the pointer is pointing somewhere, the {@linkplain Optional optional} will be set. * Otherwise, the optional will be {@linkplain Optional#empty() empty}. */ public Optional<T> dereference() { return Optional.ofNullable(impl); } /** * Set the pointer. * * @param impl The value to set the pointer to. If this is null, the pointer is unset. */ public void set(T impl) { this.impl = impl; } /** * Set the pointer to a possible value. * * @param impl The value to set the pointer to. If this is {@linkplain Optional#empty empty}, the pointer is unset. */ public void set(Optional<T> impl) { this.impl = impl.orElse(null); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/RunnableThrowsException.java
package ai.eloquent.util; /** * A {@link Runnable} that can throw an exception. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ @FunctionalInterface public interface RunnableThrowsException { /** @see Runnable#run() */ void run() throws Exception; }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/RuntimeIOException.java
package ai.eloquent.util; /** * An unchecked version of {@link java.io.IOException}. */ public class RuntimeIOException extends RuntimeException { private static final long serialVersionUID = -8572218999165094626L; /** * Creates a new exception. */ public RuntimeIOException() { } /** * Creates a new exception with a message. * * @param message the message for the exception */ public RuntimeIOException(String message) { super(message); } /** * Creates a new exception with an embedded cause. * * @param cause The cause for the exception */ public RuntimeIOException(Throwable cause) { super(cause); } /** * Creates a new exception with a message and an embedded cause. * * @param message the message for the exception * @param cause The cause for the exception */ public RuntimeIOException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/RuntimeInterruptedException.java
package ai.eloquent.util; /** * An unchecked version of {@link java.lang.InterruptedException}. Thrown by * classes that pay attention to if they were interrupted, such as the LexicalizedParser. */ public class RuntimeInterruptedException extends RuntimeException { public RuntimeInterruptedException() { super(); } public RuntimeInterruptedException(InterruptedException e) { super(e); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/SafeTimer.java
package ai.eloquent.util; import java.time.Duration; import java.util.Timer; import java.util.TimerTask; /** * This is a Timer that only accepts SafeTimerTasks as tasks. */ public interface SafeTimer { /** * This retrieves the current time on this box. This is only here so that it can be mocked. */ long now(); /** * @see Timer#schedule(TimerTask, long) */ void schedule(SafeTimerTask task, long delay); /** * @see Timer#schedule(TimerTask, long) */ default void schedule(SafeTimerTask task, Duration delay) { schedule(task, delay.toMillis()); } /** * @see Timer#schedule(TimerTask, long, long) */ void schedule(SafeTimerTask task, long delay, long period); /** * @see Timer#schedule(TimerTask, long, long) */ default void schedule(SafeTimerTask task, Duration delay, Duration period) { schedule(task, delay.toMillis(), period.toMillis()); } /** * @see Timer#scheduleAtFixedRate(TimerTask, long, long) */ void scheduleAtFixedRate(SafeTimerTask task, long delay, long period); /** * @see Timer#scheduleAtFixedRate(TimerTask, long, long) */ default void scheduleAtFixedRate(SafeTimerTask task, Duration delay, Duration period) { scheduleAtFixedRate(task, delay.toMillis(), period.toMillis()); } /** * Schedule at a fixed rate with no delay. * * @see Timer#scheduleAtFixedRate(TimerTask, long, long) */ void scheduleAtFixedRate(SafeTimerTask task, long period); /** * Schedule at a fixed rate with no delay. * * @see Timer#scheduleAtFixedRate(TimerTask, long, long) */ default void scheduleAtFixedRate(SafeTimerTask task, Duration period) { scheduleAtFixedRate(task, period.toMillis()); } /** * Cancel this timer. */ void cancel(); }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/SafeTimerMock.java
package ai.eloquent.util; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * This holds all of our timer tasks in a mocked environment, so that when we run unit tests we can guarantee that * things are getting called. */ public class SafeTimerMock implements SafeTimer { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(SafeTimerMock.class); /** * This is the static, global time shared across all SafeTimeMocks */ static long mockTime = 0; /** * This is the static, global list of all ScheduledTasks */ static final List<SafeTimerMock> timerMocks = new ArrayList<>(); /** * A lock for {@link #timerMocks}, so we can take a lock with a timeout */ private static final ReentrantLock timerLock = new ReentrantLock(); /** * A condition for some event having happened on the timer. */ private static final Condition timerCondition = timerLock.newCondition(); /** * This lets us pre-compute the tasks that will run at a given timestep */ private final static Multimap<Long, ScheduledTask> queue = ArrayListMultimap.create(); /** * This is the list of all ScheduledTasks on this SafeTimerMock */ public final List<ScheduledTask> scheduled = Collections.synchronizedList(new ArrayList<>()); public SafeTimerMock() { try { if (timerLock.tryLock(10, TimeUnit.SECONDS)) { try { timerMocks.add(this); } finally { timerLock.unlock(); } } else throw new RuntimeException("Failed to get lock in tryLock()"); } catch (InterruptedException e) { throw new RuntimeException(e); } } /** * This holds all our tasks for the timer mock */ public class ScheduledTask { public final SafeTimerTask task; public final long startTime; public final long period; public final long scheduledAt; public ScheduledTask(SafeTimerTask task, long startTime) { this(task, startTime, -1); } public ScheduledTask(SafeTimerTask task, long startTime, long period) { this.task = task; this.startTime = startTime; this.period = period; this.scheduledAt = now(); synchronized (queue) { queue.put(startTime, this); } } /** * This returns true if the ScheduledTask should be removed from the list. * * @return true if should remove */ public boolean runIfAppropriate() { if (this.task.cancelled) { return true; } // This indicated that this is a one-time thing if (this.period == -1) { if (mockTime >= this.startTime) { task.run(Optional.empty()); return true; } return false; } else { // This means that this is a recurring task if (mockTime >= this.startTime) { long offset = (mockTime - this.startTime) % period; if (offset == 0) { task.run(Optional.empty()); synchronized (queue) { queue.put(mockTime + period, this); } } } return false; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScheduledTask that = (ScheduledTask) o; return startTime == that.startTime && period == that.period && scheduledAt == that.scheduledAt && Objects.equals(task, that.task); } @Override public int hashCode() { return Objects.hash(task, startTime, period, scheduledAt); } } /** * This moves time forward in the mock timer, which will trigger any timers that need to be triggered in a synchronous * manner on this thread. */ public static void advanceTime(long millis) { boolean removedAny = false; long targetTime = mockTime + millis; while (true) { List<ScheduledTask> scheduledThisTick; try { if (timerLock.tryLock(10, TimeUnit.SECONDS)) { try { synchronized (queue) { scheduledThisTick = new ArrayList<>(queue.get(mockTime)); } List<ScheduledTask> toRemove = new ArrayList<>(); for (ScheduledTask task : scheduledThisTick) { if (task.startTime >= mockTime-1 && task.period <= 0) { toRemove.add(task); } synchronized (queue) { queue.remove(mockTime, task); queue.remove(mockTime-1, task); } } if (toRemove.size() > 0) { removedAny = true; for (SafeTimerMock timerMock : timerMocks) { timerMock.scheduled.removeAll(toRemove); } } } finally { timerLock.unlock(); } } else { log.warn("Failed to get lock in tryLock()"); return; } } catch (InterruptedException e) { throw new RuntimeException(e); } // Run the tasks after we've released the main lock for (ScheduledTask task : scheduledThisTick) { task.runIfAppropriate(); } if (mockTime < targetTime) { mockTime += 1; } else { break; } } try { if (timerLock.tryLock(10, TimeUnit.SECONDS)) { try { if (removedAny) { timerCondition.signalAll(); } } finally { timerLock.unlock(); } } else throw new RuntimeException("Failed to get lock in tryLock()"); } catch (InterruptedException e) { throw new RuntimeException(e); } } /** * This clears any previous timers we still had registered, and gets the system ready to restart */ public static void resetMockTime() { try { if (timerLock.tryLock(10, TimeUnit.SECONDS)) { try { mockTime = 0; timerMocks.clear(); } finally { timerLock.unlock(); } synchronized (queue) { queue.clear(); } } else throw new RuntimeException("Failed to get lock in tryLock()"); } catch (InterruptedException e) { throw new RuntimeException(e); } } /** * This returns the number of tasks we currently have scheduled on this SafeTimerMock. */ public int numTasksScheduled() { return scheduled.size(); } /** * This blocks the calling thread until there are no outstanding tasks on this SafeTimerMock running, then continues. * * This will time out after 5 virtual "minutes" of waiting period. */ public void waitForSilence() { log.info("[{}] Waiting for SafeTimerMock to flush. scheduled={}", mockTime, numTasksScheduled()); long startTime = now(); long lastMessageTime = startTime; try { if (timerLock.tryLock(10, TimeUnit.SECONDS)) { try { int i = 0; while (numTasksScheduled() > 0 && i < 10000) { i += 1; try { timerCondition.await(1, TimeUnit.SECONDS); // Hooray, we've successfully got silence if (numTasksScheduled() == 0) { Uninterruptably.sleep(10); if (numTasksScheduled() == 0) { break; } } // Log if the queue hasn't flushed in long enough [virtual time] if (now() > lastMessageTime + 60000) { log.warn("[{}] Have not flushed transport after {}; scheduled={}", mockTime, TimerUtils.formatTimeDifference(now() - startTime), numTasksScheduled()); lastMessageTime = now(); } // Exception if the queue doesn't flush in 5 [virtual] minutes seconds if (now() > startTime + Duration.ofMinutes(5).toMillis()) { throw new IllegalStateException("Transport hasn't flushed in 5 minutes. This almost certainly means a deadlock somewhere. " + "now=" + mockTime + "; queue size=" + numTasksScheduled()); } } catch (InterruptedException e) { log.warn("Interrupt waiting on transport. Transport still has {} scheduled events", numTasksScheduled()); } } if (numTasksScheduled() > 0) { log.warn("There are still tasks scheduled after {} iterations of waiting; this is from a race condition on the timer", i); } } finally { timerLock.unlock(); } } else throw new RuntimeException("Failed to get lock in tryLock()"); } catch (InterruptedException e) { throw new RuntimeException(e); } log.info("[{}] Transport is flushed (scheduled={} real_flush_time={})", mockTime, numTasksScheduled(), TimerUtils.formatTimeDifference(now() - startTime)); } /** * Get the current time on the timer mock. */ public static long time() { return mockTime; } /** * This retrieves the current time on this box. This is only here so that it can be mocked. */ @Override public long now() { return mockTime; } /** * This allows outside code to access the timer lock, in case they need to do things that can't allow time to slip */ public void withTimerLock(Runnable runnable) { try { if (timerLock.tryLock(10, TimeUnit.SECONDS)) { try { runnable.run(); } finally { timerLock.unlock(); } } else throw new RuntimeException("Failed to get lock in tryLock()"); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } } @Override public void schedule(SafeTimerTask task, long delay) { try { if (timerLock.tryLock(10, TimeUnit.SECONDS)) { try { // If we don't schedule this inside the lock, it's possible for time to slip past us while we're scheduling, and // then this event will never be run. ScheduledTask scheduledTask = new ScheduledTask(task, mockTime + delay); scheduled.add(scheduledTask); } finally { timerLock.unlock(); } } else throw new RuntimeException("Failed to get lock in tryLock()"); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } } @Override public void schedule(SafeTimerTask task, long delay, long period) { try { if (timerLock.tryLock(10, TimeUnit.SECONDS)) { try { // If we don't schedule this inside the lock, it's possible for time to slip past us while we're scheduling, and // then this event will never be run. ScheduledTask scheduledTask = new ScheduledTask(task, mockTime + delay, period); task.registerCancelCallback(() -> { try { if (timerLock.tryLock(10, TimeUnit.SECONDS)) { try { scheduled.remove(scheduledTask); timerCondition.signalAll(); } finally { timerLock.unlock(); } } else { throw new IllegalStateException("Could not take lock on timer cancel for 10 seconds"); } } catch (InterruptedException e) { throw new RuntimeException(e); } }); scheduled.add(scheduledTask); } finally { timerLock.unlock(); } } else throw new RuntimeException("Failed to get lock in tryLock()"); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } } @Override public void scheduleAtFixedRate(SafeTimerTask task, long delay, long period) { schedule(task, delay, period); } @Override public void scheduleAtFixedRate(SafeTimerTask task, long period) { scheduleAtFixedRate(task, 0, period); } @Override public void cancel() { try { if (timerLock.tryLock(10, TimeUnit.SECONDS)) { try { timerMocks.remove(this); List<ScheduledTask> scheduledCopy = new ArrayList<>(scheduled); for (ScheduledTask task : scheduledCopy) { task.task.cancel(); } scheduled.clear(); timerCondition.signalAll(); } finally { timerLock.unlock(); } } else throw new RuntimeException("Failed to get lock in tryLock()"); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/SafeTimerReal.java
package ai.eloquent.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.Timer; /** * Created by keenon on 2/16/18. */ public class SafeTimerReal implements SafeTimer { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(SafeTimer.class); Timer timer; public SafeTimerReal() { timer = new Timer("SafeTimerReal", true); } /** * This retrieves the current time on this box. This is only here so that it can be mocked. */ @Override public long now() { return System.currentTimeMillis(); } @Override public void schedule(SafeTimerTask task, long delay) { timer.schedule(task, delay); } @Override public void schedule(SafeTimerTask task, long delay, long period) { timer.schedule(task, delay, period); } @Override public void scheduleAtFixedRate(SafeTimerTask task, long delay, long period) { timer.schedule(task, delay, period); } @Override public void scheduleAtFixedRate(SafeTimerTask task, long period) { scheduleAtFixedRate(task, 0, period); } @Override public void cancel() { timer.cancel(); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/SafeTimerTask.java
package ai.eloquent.util; import ai.eloquent.raft.RaftLifecycle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.TimerTask; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; /** * All TimerTask objects crash their parent thread when they throw an exception, so we wrap timers in SafeTimerTask * objects, which don't. */ // NOTE[gabor]: If you change this class, also re-run SafeTimerTaskTest. The test is flaky on CI, but runs reliably locally. See #150 public abstract class SafeTimerTask extends TimerTask { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(SafeTimerTask.class); /** * A thread pool for our timer tasks. */ private static final Lazy<ExecutorService> POOL = Lazy.of(() -> RaftLifecycle.global.managedThreadPool("timertask")); /** * If true, this task has been cancelled. */ public boolean cancelled = false; /** * A set of functions called when we cancel this timer task. */ private final List<Runnable> onCancelCallbacks = new ArrayList<>(); /** * This is the count of runs of this timertask that are simultaneously processing */ private AtomicInteger runningCount = new AtomicInteger(0); /** * This is the maximum number of simultaneous runs of this task that we'll allow. Any runs beyond this count will be * dropped on the floor, and will issue an error. */ public static final int MAX_SIMULTANEOUS_RUNS = 1; /** {@inheritDoc} */ @Override public void run() { run(Optional.of(pool())); } /** * Run this job on an optional pool. * @param pool The executor pool to run on. */ public void run(Optional<Executor> pool) { if (this.cancelled) { return; } if (!pool.isPresent()) { try { runUnsafe(); } catch (Throwable e) { // We don't rethrow the exception, because that kills the global timer log.warn("SafeTimerTask caught a thrown exception.", e); } } else { Executor executor = pool.get(); try { if (!(executor instanceof ExecutorService) || (!((ExecutorService) executor).isTerminated() && !((ExecutorService) executor).isShutdown())) { if (runningCount.incrementAndGet() <= MAX_SIMULTANEOUS_RUNS) { try { pool.get().execute(() -> { try { runUnsafe(); } catch (Throwable e) { // We don't rethrow the exception, because that kills the global timer log.warn("SafeTimerTask caught a thrown exception.", e); } finally { runningCount.decrementAndGet(); } }); } catch (Throwable t) { runningCount.decrementAndGet(); log.warn("Could not submit timer task to pool: ", t); } } else { int numberRunning = runningCount.decrementAndGet(); if (numberRunning >= 5) { log.warn("SafeTimerTask is not running request, because we already have {} running", numberRunning); } else { log.debug("SafeTimerTask is not running request, because we already have {} running", numberRunning); } } } else { log.warn("Trying to run a task even though our managedThreadPool for running tasks has been shut down."); } } catch (Throwable t) { // We don't rethrow the exception, because that kills the global timer log.warn("SafeTimerTask caught an exception when starting a thread to execute an event.", t); } } } /** * Run this task on the given pool. An alias for {@link #run(Optional)}. * * @param pool The pool to run on. */ public void run(Executor pool) { this.run(Optional.of(pool)); } /** * Sometimes we want to be notified when things cancel. */ public void registerCancelCallback(Runnable runnable) { this.onCancelCallbacks.add(runnable); } /** {@inheritDoc} */ @Override public boolean cancel() { boolean retVal = super.cancel(); for (Runnable callbacks: onCancelCallbacks) { callbacks.run(); } cancelled = true; // always cancel return retVal; } /** * An overwritable function for getting the pool that we should run this timer's tasks on. */ protected ExecutorService pool() { return POOL.get(); } /** * The implementation of the task, except that we are allowed to throw arbitrary exceptions. * * @throws Throwable An exception that this runner is allowed to throw. */ public abstract void runUnsafe() throws Throwable; }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/Span.java
package ai.eloquent.util; import java.io.Serializable; import java.util.Iterator; import java.util.NoSuchElementException; /** * A span, inclusive of {@link Span#begin} and exclusive of {@link Span#end}. * * @author gabor */ public class Span implements Iterable<Long>, Comparable<Span>, Serializable { /** The signature for serializing this version of this class. */ private static final long serialVersionUID = 1L; /** The beginning of this span, inclusive. */ public final long begin; /** The end of this span, exclusive. */ public final long end; /** * Create a new span from two values. * * @param begin The beginning of the span, inclusive. * @param end The end of the span, exclusive. */ public Span(long begin, long end) { this.begin = begin; this.end = end; } /** * Returns true if this span contains the argument span. * This includes the case when the two spans are the same. * * @param other The other span. * @return True if the argument span is contained in this span. */ public boolean contains(Span other) { return this.begin <= other.begin && this.end >= other.end; } /** * The length of this span -- i.e., the distance from {@link Span#begin} to {@link Span#end}. */ public long length() { return end - begin; } /** * Returns true if there's any overlap between this span and the argument span. * * @param other The other span to compare this span to. * @return True if this and the other span have any overlap. */ public boolean overlaps(Span other) { //noinspection SimplifiableIfStatement if (this.begin == this.end || other.begin == other.end) { return false; // length 0 spans can't overlap } return this.contains(other) || other.contains(this) || (this.end > other.end && this.begin < other.end) || (other.end > this.end && other.begin < this.end) || this.equals(other); } /** * Returns the amount of overlap between this span and the argument span. * * @param other The argument span. * @return The number of tokens that overlap between the two spans. */ public long overlap(Span other) { if (this.contains(other) || other.contains(this)) { return Math.min(this.end - this.begin, other.end - other.begin); } else if ((this.end > other.end && this.begin < other.end) || (other.end > this.end && other.begin < this.end)) { return Math.min(this.end, other.end) - Math.max(this.begin, other.begin); } else { return 0; } } /** * Returns the intersection between two spans. * * @param a The first span. * @param b The second span. * * @return A span denoting the intersection between the two spans. */ public static Span intersect(Span a, Span b) { long newStart = Math.max(a.begin, b.begin); long newEnd = Math.min(a.end, b.end); if (newStart < newEnd) { return new Span(newStart, newEnd); } else if (a.begin == b.end) { return new Span(a.begin, a.begin); } else if (a.end == b.begin) { return new Span(a.end, a.end); } else { return new Span(0, 0); } } /** * Create a span from two values. * * @param a One of the values (not necessarily the smaller). * @param b The other value (not necessarily bigger). * * @return The span between a and b. */ public static Span fromValues(long a, long b) { if (a < b) { return new Span(a, b); } else { return new Span(b, a); } } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Span span = (Span) o; return begin == span.begin && end == span.end; } /** {@inheritDoc} */ @Override public int hashCode() { return ((int) begin) ^ ((int) end); } /** {@inheritDoc} */ @Override public String toString() { return "[" + begin + ", " + end + ")"; } /** {@inheritDoc} */ @Override public Iterator<Long> iterator() { return new Iterator<Long>() { private long i = begin; @Override public boolean hasNext() { return i < end; } @Override public Long next() { if (!hasNext()) { throw new NoSuchElementException(); } i += 1; return i - 1; } }; } /** {@inheritDoc} */ @Override public int compareTo(Span o) { int pass1 = Long.compare(this.begin, o.begin); if (pass1 != 0) { return pass1; } return Long.compare(this.end, o.end); } /** * If true, the value is contined in the span. * This is defined with an <b>inclusive</b> begin index and an * <b>exclusive</b> end index. * * @param i The value we are checking. * * @return True if begin &lt;= i &lt; end. */ public boolean contains(int i) { return i >= this.begin && i < this.end; } /** * The middle (average?) of the span. That is, (end + begin / 2). */ public long middle() { return (end + begin) / 2; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/StackTrace.java
package ai.eloquent.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * A stack trace, with the appropriate formatting and {@link Object#equals(Object)} and {@link Object#hashCode()} * defined so that we can, e.g., store them in a set. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class StackTrace { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(StackTrace.class); /** * The actual stack trace. */ private final List<StackTraceElement> trace; /** * A rendered representation of the stack trace. */ private final String repr; /** * Create a stack trace from the current trace. */ public StackTrace() { this(Thread.currentThread().getStackTrace()); } /** * Create a stack trace from a given trace array. * * @param trace The stack trace we're representing */ public StackTrace(StackTraceElement[] trace) { this(Arrays.asList(trace)); } /** * Create a stack trace from a given trace array. * * @param trace The stack trace we're representing */ public StackTrace(List<StackTraceElement> trace) { this.trace = trace; StringBuilder b = new StringBuilder(); for (StackTraceElement elem : trace) { if (elem.getClassName().equals(StackTrace.class.getName())) { continue; // ignore this class } if (elem.getClassName().equals(Thread.class.getName())) { continue; // ignore Thread class } b.append(elem.getClassName() .replaceAll("^ai.eloquent.", "") .replaceAll("^java.lang.", "") .replaceAll("^java.util.", "j.u.") .replaceAll("^org.eclipse.jetty.", "jetty.") ).append('.').append(elem.getMethodName()); if (elem.getLineNumber() >= 0) { b.append(" @ ").append(elem.getLineNumber()); } else { b.append(" @ ???"); } b.append("\n"); } this.repr = b.toString().trim(); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StackTrace that = (StackTrace) o; return Objects.equals(repr, that.repr); } /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(repr); } /** {@inheritDoc} */ @Override public String toString() { return this.repr; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/StringUtils.java
package ai.eloquent.util; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.function.Function; import java.util.stream.Stream; public class StringUtils { public static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * Joins each elem in the {@link Iterable} with the given glue. * For example, given a list of {@code Integers}, you can create * a comma-separated list by calling {@code join(numbers, ", ")}. */ public static <X> String join(Iterable<X> l, String glue) { StringBuilder sb = new StringBuilder(); boolean first = true; for (X o : l) { if (!first) { sb.append(glue); } else { first = false; } sb.append(o); } return sb.toString(); } /** * Joins each elem in the array with the given glue. For example, given a * list of ints, you can create a comma-separated list by calling * {@code join(numbers, ", ")}. */ public static String join(Object[] elements, String glue) { return (join(Arrays.asList(elements), glue)); } /** * Joins an array of elements in a given span. * @param elements The elements to join. * @param start The start index to join from. * @param end The end (non-inclusive) to join until. * @param glue The glue to hold together the elements. * @return The string form of the sub-array, joined on the given glue. */ public static String join(Object[] elements, int start, int end, String glue) { StringBuilder b = new StringBuilder(127); boolean isFirst = true; for (int i = start; i < end; ++i) { if (isFirst) { b.append(elements[i]); isFirst = false; } else { b.append(glue).append(elements[i]); } } return b.toString(); } /** * Joins each elem in the given String[] array with the given glue. * For example, given a list of {@code Integers}, you can create * a comma-separated list by calling {@code join(numbers, ", ")}. */ public static String join(String[] items, String glue) { return join(Arrays.asList(items), glue); } public static <E> String join(List<? extends E> l, String glue, Function<E,String> toStringFunc, int start, int end) { StringBuilder sb = new StringBuilder(); boolean first = true; start = Math.max(start, 0); end = Math.min(end, l.size()); for (int i = start; i < end; i++) { if ( ! first) { sb.append(glue); } else { first = false; } sb.append(toStringFunc.apply(l.get(i))); } return sb.toString(); } /** * Joins each elem in the {@link Stream} with the given glue. * For example, given a list of {@code Integers}, you can create * a comma-separated list by calling {@code join(numbers, ", ")}. * * @see StringUtils#join(Iterable, String) */ public static <X> String join(Stream<X> l, String glue) { StringBuilder sb = new StringBuilder(); boolean first = true; Iterator<X> iter = l.iterator(); while (iter.hasNext()) { if ( ! first) { sb.append(glue); } else { first = false; } sb.append(iter.next()); } return sb.toString(); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/SystemUtils.java
package ai.eloquent.util; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Optional; public class SystemUtils { /** * The hostname of this machine */ public static final String HOST; static { // Get the hostname String host; try { host = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { host = Optional.ofNullable(System.getenv("HOST")).orElse("unknown_host"); } if (host.contains("/")) { host = host.substring(0, host.indexOf('/')); } HOST = host; } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/ThrowableSupplier.java
package ai.eloquent.util; import java.util.function.Supplier; /** * A supplier which can throw an exception. * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ @FunctionalInterface public interface ThrowableSupplier<E> { /** * @see Supplier#get() */ E get() throws Throwable; }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/TimerUtils.java
package ai.eloquent.util; import java.time.Instant; /** * Utilities for working with time. * God I hate time. * * @author Gabor Angeli */ public class TimerUtils { /** * UNIT TESTS ONLY. * Setting this to true will set the time to Thu Nov 02 2017 15:50:00 PT */ public static boolean mockNow = false; /** * A wrapper for {@link Instant#now()} that allows for mocking a particular time. */ public static Instant mockableNow() { if (mockNow) { return Instant.ofEpochMilli(1509651000000L); } else { return Instant.now(); } } /** * Utility method for formatting a time difference (maybe this should go to a util class?) * @param diff Time difference in milliseconds * @param b The string builder to append to */ public static void formatTimeDifference(long diff, StringBuilder b){ //--Short circuit for < 100ms if (diff < 100) { b.append(diff).append(" ms"); return; } //--Get Values int mili = (int) diff % 1000; long rest = diff / 1000; int sec = (int) rest % 60; rest = rest / 60; int min = (int) rest % 60; rest = rest / 60; int hr = (int) rest % 24; rest = rest / 24; int day = (int) rest; //--Make String if(day > 0) b.append(day).append(day > 1 ? " days, " : " day, "); if(hr > 0) b.append(hr).append(hr > 1 ? " hours, " : " hour, "); if(min > 0) { if(min < 10){ b.append("0"); } b.append(min).append(":"); } if(min > 0 && sec < 10){ b.append("0"); } if (day == 0 && hr == 0 && min == 0 && sec < 30) { b.append(sec).append("."); if (mili >= 100) { b.append(mili); } else if (mili >= 10) { b.append("0").append(mili); } else { b.append("00").append(mili); } } else { b.append(sec); } if(min > 0) b.append(" minutes"); else b.append(" seconds"); } /** * Format a time difference (duration) in a human-readable format. * * @param diff The difference in milliseconds between two timestamps. * * @return A human-readable debug string of this time difference. */ public static String formatTimeDifference(long diff){ StringBuilder b = new StringBuilder(); formatTimeDifference(diff, b); return b.toString(); } /** * Format the amount of time that has elapsed since the argument time. * * @param startTime The time we started measuring from. * * @return A human-readable debug string of the elapsed time. */ public static String formatTimeSince(long startTime){ return formatTimeDifference(System.currentTimeMillis() - startTime); } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/Uninterruptably.java
package ai.eloquent.util; import ai.eloquent.util.RuntimeInterruptedException; import java.time.Duration; /** * Created by keenon on 11/27/16. * * It turns out Thread.sleep() isn't guaranteed to wait the whole time, and can get woken up at random moments. If you * really want the behavior that almost everyone wants (sleep as long as I told you to, not as long as you feel like) * then you need to wrap sleep in a while() loop that checks the clock. This class does that. */ public class Uninterruptably { /** * Sleep for a given amount of time, not allowing for interrupts to shorten the time. * * @param millis The amount of time to sleep for. */ public static void sleep(long millis) { if (millis <= 0) { return; } long sleepTill = System.currentTimeMillis() + millis; while (System.currentTimeMillis() < sleepTill) { try { long sleepTime = sleepTill - System.currentTimeMillis(); if (sleepTime > 0) { Thread.sleep(sleepTime); } } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); // we still want to be able to interrupt, we just don't care if it's a real exception. } } } /** * A helper for {@link #sleep(long)} */ public static void sleep(Duration duration) { sleep(duration.toMillis()); } /** * Join with a thread, retrying the join if we are interrupted. * * @param t The thread to join. */ public static void join(Thread t) { // Try joining try { t.join(); } catch (InterruptedException e) { // Retry if we were interrupted join(t); } // Retry if we are still alive if (t.isAlive()) { join(t); } } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/util/ZipUtils.java
package ai.eloquent.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.zip.DeflaterInputStream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.InflaterInputStream; /** * Some utilities with working with GZip streams * * @author <a href="mailto:gabor@eloquent.ai">Gabor Angeli</a> */ public class ZipUtils { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(ZipUtils.class); /** * Zip a byte stream. */ public static byte[] gzip(byte[] unzipped) throws RuntimeIOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { try (GZIPOutputStream stream = new GZIPOutputStream(out)) { stream.write(unzipped); } catch (IOException e) { log.error("gzip threw an exception on a byte array stream", e); throw new RuntimeIOException(e); } return out.toByteArray(); } catch (IOException e) { log.error("Could not close byte array output stream", e); throw new RuntimeIOException(e); } } /** * Zip a byte stream. */ public static InputStream zipStream(InputStream unzipped) { return new DeflaterInputStream(unzipped); } /** * Unzip a byte stream. */ public static InputStream unzipStream(InputStream zipped) { return new InflaterInputStream(zipped); } /** Copy from an input stream to an output stream */ public static long copy(InputStream src, OutputStream sink) throws IOException { byte[] buf = new byte[1024]; long total = 0L; while(true) { int count = src.read(buf); if (count == -1) { return total; } sink.write(buf, 0, count); total += (long) count; } } /** * Unzip a byte stream. */ public static byte[] gunzip(byte[] zipped) throws RuntimeIOException { try (ByteArrayInputStream in = new ByteArrayInputStream(zipped)) { try (GZIPInputStream stream = new GZIPInputStream(in)) { try (ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(32, stream.available()))) { copy(stream, out); return out.toByteArray(); } } } catch (IOException e) { log.error("gunzip threw an exception on a byte array stream", e); throw new RuntimeIOException(e); } } }
0
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent
java-sources/ai/eloquent/theseus/0.3.0/ai/eloquent/web/TrackedExecutorService.java
package ai.eloquent.web; import ai.eloquent.error.RaftErrorListener; import ai.eloquent.monitoring.Prometheus; import ai.eloquent.stats.IntCounter; import ai.eloquent.util.StackTrace; import ai.eloquent.util.SystemUtils; import ai.eloquent.util.TimerUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.util.*; import java.util.concurrent.*; import java.util.stream.Collectors; /** * A wrapper around an executor service that tracks our threads. */ public class TrackedExecutorService implements ExecutorService { /** * An SLF4J Logger for this class. */ private static final Logger log = LoggerFactory.getLogger(TrackedExecutorService.class); /** Keeps track of existing {@link RaftErrorListener} **/ private static ArrayList<RaftErrorListener> errorListeners = new ArrayList<>(); /** * Keeps track of an additional {@link RaftErrorListener} in this class * @param errorListener */ public void addErrorListener(RaftErrorListener errorListener) { errorListeners.add(errorListener); } /** * Stop listening from a specific {@link RaftErrorListener} * @param errorListener The error listener to be removed */ public void removeErrorListener(RaftErrorListener errorListener) { errorListeners.remove(errorListener); } /** * Clears all the {@link RaftErrorListener}s attached to this class. */ public void clearErrorListeners() { errorListeners.clear(); } /** * Alert each of the {@link RaftErrorListener}s attached to this class. */ private void throwRaftError(String incidentKey, String debugMessage) { errorListeners.forEach(listener -> listener.accept(incidentKey, debugMessage, Thread.currentThread().getStackTrace())); } /** The implementing executor */ private final ExecutorService impl; /** The number of elements currently in the queue. */ private final String name; /** The number of elements currently in the queue. */ private final Object gaugeQueueSize; /** The number of tasks ever run on this executor. */ private final Object counterTaskCount; /** The runtime of tasks in this executor. */ private final Object summaryRuntime; /** The amount of time threads spend in the queue before starting. */ private final Object summaryQueueTime; /** The last time we issued a page, to prevent spamming PagerDuty. */ private long lastPaged = 0L; /** The last time we issued a page, to prevent spamming PagerDuty. */ private long pageAboveThreadCount = 128L; /** Create a tracked executor */ public TrackedExecutorService(String name, ExecutorService impl) { this.impl = impl; this.name = name.replace('-', '_').replace(' ', '_'); gaugeQueueSize = Prometheus.gaugeBuild(this.name + "_queue_size","The number of tasks currently in pool " + this.name); counterTaskCount = Prometheus.counterBuild(this.name + "_total_tasks", "The number of tasks that have run in pool " + this.name); summaryRuntime = Prometheus.summaryBuild(this.name + "_runtime", "The time it takes for tasks to run in pool " + this.name); summaryQueueTime = Prometheus.summaryBuild(this.name + "_queuetime", "The time it takes for tasks to be scheduled in pool " + this.name); } /** * Page if we have more than the argument number of threads in the thread pool. * * @param count The number of threads above which to send a page (non-inclusive) */ public void pageAboveThreadCount(int count) { this.pageAboveThreadCount = Math.max(1, count); } /** * Keep track of the queue size, paging if it gets too large. */ private void checkQueueSize() { Double queueSize = Prometheus.gaugeGet(this.gaugeQueueSize); if (this.impl instanceof ThreadPoolExecutor && queueSize > 128) { synchronized (TrackedExecutorService.this) { // 1. Don't duplicate page if (queueSize < this.pageAboveThreadCount || System.currentTimeMillis() < lastPaged + 600000) { // don't duplicate page return; } this.lastPaged = System.currentTimeMillis(); log.warn("A queue has more than 64 threads waiting on it: {} -- paging PagerDuty", queueSize); // 2. Get all the threads in this pool Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces(); IntCounter<List<StackTraceElement>> inThisPool = new IntCounter<>(); for (Map.Entry<Thread, StackTraceElement[]> entry : threads.entrySet()) { if (entry.getKey().getName().startsWith(this.name)) { inThisPool.incrementCount(Arrays.asList(entry.getValue())); } } // 3. Convert traces to Strings IntCounter<String> traces = new IntCounter<>(); for (Map.Entry<List<StackTraceElement>, Integer> entry : inThisPool.entrySet()) { traces.setCount(new StackTrace(entry.getKey()).toString(), entry.getValue()); } // 4. Page if (traces.totalIntCount() >= 128) { // make sure we empirically have > 128 pages String incidentKey = "thread-overload-" + this.name + SystemUtils.HOST; throwRaftError(incidentKey, "Too many threads on " + this.name); } } } } /** * Wrap a runnable in our metrics */ private Runnable wrap(Runnable task) { Object timerQueueTimer = Prometheus.startTimer(summaryQueueTime); Prometheus.gaugeInc(gaugeQueueSize); Prometheus.counterInc(counterTaskCount); checkQueueSize(); // StackTraceElement[] callerTrace = Thread.currentThread().getStackTrace(); return () -> { Prometheus.observeDuration(timerQueueTimer); Object timerRunTimer = Prometheus.startTimer(summaryRuntime); try { task.run(); } finally { Prometheus.gaugeDec(gaugeQueueSize); Double duration = Prometheus.observeDuration(timerRunTimer); if (duration > 60.0 && duration != null) { log.warn("Thread on executor {} took >1m to finish ({})", this.name, TimerUtils.formatTimeDifference(duration.longValue() * 1000)); // this.name, TimeUtils.formatTimeDifference((long) duration * 1000), new StackTrace(callerTrace)); } } }; } /** * Wrap a callable in our metrics */ private <T> Callable<T> wrap(Callable<T> task) { Object timerQueueTimer = Prometheus.startTimer(summaryQueueTime); checkQueueSize(); Prometheus.gaugeInc(gaugeQueueSize); Prometheus.counterInc(counterTaskCount); return () -> { Prometheus.observeDuration(timerQueueTimer); Object timerRunTimer = Prometheus.startTimer(summaryRuntime); try { return task.call(); } finally { Prometheus.gaugeDec(gaugeQueueSize); Prometheus.observeDuration((timerRunTimer)); } }; } /** {@inheritDoc} */ @Override public void shutdown() { impl.shutdown(); } /** {@inheritDoc} */ @Nonnull @Override public List<Runnable> shutdownNow() { return impl.shutdownNow(); } /** {@inheritDoc} */ @Override public boolean isShutdown() { return impl.isShutdown(); } /** {@inheritDoc} */ @Override public boolean isTerminated() { return impl.isTerminated(); } /** {@inheritDoc} */ @Override public boolean awaitTermination(long timeout, @Nonnull TimeUnit unit) throws InterruptedException { return impl.awaitTermination(timeout, unit); } /** {@inheritDoc} */ @Nonnull @Override public <T> Future<T> submit(@Nonnull Callable<T> task) { return impl.submit(wrap(task)); } /** {@inheritDoc} */ @Nonnull @Override public <T> Future<T> submit(@Nonnull Runnable task, T result) { return impl.submit(wrap(task), result); } /** {@inheritDoc} */ @Nonnull @Override public Future<?> submit(@Nonnull Runnable task) { return impl.submit(wrap(task)); } /** {@inheritDoc} */ @Nonnull @Override public <T> List<Future<T>> invokeAll(@Nonnull Collection<? extends Callable<T>> tasks) throws InterruptedException { return impl.invokeAll(tasks.stream().map(this::wrap).collect(Collectors.toList())); } /** {@inheritDoc} */ @Nonnull @Override public <T> List<Future<T>> invokeAll(@Nonnull Collection<? extends Callable<T>> tasks, long timeout, @Nonnull TimeUnit unit) throws InterruptedException { return impl.invokeAll(tasks.stream().map(this::wrap).collect(Collectors.toList()), timeout, unit); } /** {@inheritDoc} */ @Nonnull @Override public <T> T invokeAny(@Nonnull Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return impl.invokeAny(tasks.stream().map(this::wrap).collect(Collectors.toList())); } /** {@inheritDoc} */ @Override public <T> T invokeAny(@Nonnull Collection<? extends Callable<T>> tasks, long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return impl.invokeAny(tasks.stream().map(this::wrap).collect(Collectors.toList()), timeout, unit); } /** {@inheritDoc} */ @Override public void execute(@Nonnull Runnable command) { impl.execute(wrap(command)); } /** {@inheritDoc} */ @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @Override public boolean equals(Object o) { return impl.equals(o); } /** {@inheritDoc} */ @Override public int hashCode() { return impl.hashCode(); } /** {@inheritDoc} */ @Override public String toString() { return impl.toString(); } }
0
java-sources/ai/engagely/openbot/1.0.16/ai/engagely/openbot/model/utils
java-sources/ai/engagely/openbot/1.0.16/ai/engagely/openbot/model/utils/helpers/TouchImageView.java
package ai.engagely.openbot.model.utils.helpers; import android.content.Context; import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import androidx.appcompat.widget.AppCompatImageView; public class TouchImageView extends AppCompatImageView implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener { Matrix matrix; // We can be in one of these 3 states static final int NONE = 0; static final int DRAG = 1; static final int ZOOM = 2; int mode = NONE; // Remember some things for zooming PointF last = new PointF(); PointF start = new PointF(); float minScale = 1f; float maxScale = 3f; float[] m; int viewWidth, viewHeight; static final int CLICK = 3; float saveScale = 1f; protected float origWidth, origHeight; int oldMeasuredWidth, oldMeasuredHeight; ScaleGestureDetector mScaleDetector; Context context; public TouchImageView(Context context) { super(context); sharedConstructing(context); } public TouchImageView(Context context, AttributeSet attrs) { super(context, attrs); sharedConstructing(context); } GestureDetector mGestureDetector; private void sharedConstructing(Context context) { super.setClickable(true); this.context = context; mGestureDetector = new GestureDetector(context, this); mGestureDetector.setOnDoubleTapListener(this); mScaleDetector = new ScaleGestureDetector(context, new ScaleListener()); matrix = new Matrix(); m = new float[9]; setImageMatrix(matrix); setScaleType(ScaleType.MATRIX); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mScaleDetector.onTouchEvent(event); mGestureDetector.onTouchEvent(event); PointF curr = new PointF(event.getX(), event.getY()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: last.set(curr); start.set(last); mode = DRAG; break; case MotionEvent.ACTION_MOVE: if (mode == DRAG) { float deltaX = curr.x - last.x; float deltaY = curr.y - last.y; float fixTransX = getFixDragTrans(deltaX, viewWidth, origWidth * saveScale); float fixTransY = getFixDragTrans(deltaY, viewHeight, origHeight * saveScale); matrix.postTranslate(fixTransX, fixTransY); fixTrans(); last.set(curr.x, curr.y); } break; case MotionEvent.ACTION_UP: mode = NONE; int xDiff = (int) Math.abs(curr.x - start.x); int yDiff = (int) Math.abs(curr.y - start.y); if (xDiff < CLICK && yDiff < CLICK) performClick(); break; case MotionEvent.ACTION_POINTER_UP: mode = NONE; break; } setImageMatrix(matrix); invalidate(); return true; // indicate event was handled } }); } public void setMaxZoom(float x) { maxScale = x; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { return false; } @Override public boolean onDoubleTap(MotionEvent e) { // Double tap is detected Log.i("MAIN_TAG", "Double tap detected"); float origScale = saveScale; float mScaleFactor; if (saveScale == maxScale) { saveScale = minScale; mScaleFactor = minScale / origScale; } else { saveScale = maxScale; mScaleFactor = maxScale / origScale; } matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2, viewHeight / 2); fixTrans(); return false; } @Override public boolean onDoubleTapEvent(MotionEvent e) { return false; } @Override public boolean onDown(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScaleBegin(ScaleGestureDetector detector) { mode = ZOOM; return true; } @Override public boolean onScale(ScaleGestureDetector detector) { float mScaleFactor = detector.getScaleFactor(); float origScale = saveScale; saveScale *= mScaleFactor; if (saveScale > maxScale) { saveScale = maxScale; mScaleFactor = maxScale / origScale; } else if (saveScale < minScale) { saveScale = minScale; mScaleFactor = minScale / origScale; } if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight) matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2, viewHeight / 2); else matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY()); fixTrans(); return true; } } void fixTrans() { matrix.getValues(m); float transX = m[Matrix.MTRANS_X]; float transY = m[Matrix.MTRANS_Y]; float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale); float fixTransY = getFixTrans(transY, viewHeight, origHeight * saveScale); if (fixTransX != 0 || fixTransY != 0) matrix.postTranslate(fixTransX, fixTransY); } float getFixTrans(float trans, float viewSize, float contentSize) { float minTrans, maxTrans; if (contentSize <= viewSize) { minTrans = 0; maxTrans = viewSize - contentSize; } else { minTrans = viewSize - contentSize; maxTrans = 0; } if (trans < minTrans) return -trans + minTrans; if (trans > maxTrans) return -trans + maxTrans; return 0; } float getFixDragTrans(float delta, float viewSize, float contentSize) { if (contentSize <= viewSize) { return 0; } return delta; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); viewWidth = MeasureSpec.getSize(widthMeasureSpec); viewHeight = MeasureSpec.getSize(heightMeasureSpec); // // Rescales image on rotation // if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0) return; oldMeasuredHeight = viewHeight; oldMeasuredWidth = viewWidth; if (saveScale == 1) { // Fit to screen. float scale; Drawable drawable = getDrawable(); if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) return; int bmWidth = drawable.getIntrinsicWidth(); int bmHeight = drawable.getIntrinsicHeight(); Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight); float scaleX = (float) viewWidth / (float) bmWidth; float scaleY = (float) viewHeight / (float) bmHeight; scale = Math.min(scaleX, scaleY); matrix.setScale(scale, scale); // Center the image float redundantYSpace = (float) viewHeight - (scale * (float) bmHeight); float redundantXSpace = (float) viewWidth - (scale * (float) bmWidth); redundantYSpace /= (float) 2; redundantXSpace /= (float) 2; matrix.postTranslate(redundantXSpace, redundantYSpace); origWidth = viewWidth - 2 * redundantXSpace; origHeight = viewHeight - 2 * redundantYSpace; setImageMatrix(matrix); } fixTrans(); } }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/ApacheAsyncHttpSender.java
package ai.engageminds.sdk; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.concurrent.FutureCallback; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.nio.client.HttpAsyncClient; import org.apache.http.util.EntityUtils; import java.util.function.BiConsumer; /** * default implement of HttpSender with ApacheAsyncHttpClient */ public class ApacheAsyncHttpSender implements HttpSender { private final HttpAsyncClient httpClient; private final RequestConfig reqCfg; public ApacheAsyncHttpSender() { this(HttpAsyncClients.custom() .setMaxConnPerRoute(1000) .setMaxConnTotal(10000) .build()); } public ApacheAsyncHttpSender(CloseableHttpAsyncClient httpClient) { this(httpClient, null); } public ApacheAsyncHttpSender(CloseableHttpAsyncClient httpClient, RequestConfig reqCfg) { this.httpClient = httpClient; if (!httpClient.isRunning()) { httpClient.start(); } if (reqCfg != null) { this.reqCfg = reqCfg; return; } this.reqCfg = RequestConfig.custom() .setRedirectsEnabled(false) .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setConnectionRequestTimeout(3000) .setConnectTimeout(3000) .setSocketTimeout(5000) .build(); } @Override public void send(Request req, BiConsumer<Response, Exception> cb) { HttpPost post = new HttpPost(req.getUrl()); post.setConfig(reqCfg); post.setHeader("User-Agent", UA); if (req.getCompress() != null) { post.setHeader("Content-Encoding", req.getCompress()); } post.setEntity(new ByteArrayEntity(req.getBody(), ContentType.APPLICATION_JSON)); httpClient.execute(post, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse res) { StatusLine sl = res.getStatusLine(); HttpEntity resEntity = res.getEntity(); try { Response rv = new Response(); rv.setStatusCode(sl.getStatusCode()); rv.setReasonPhrase(sl.getReasonPhrase()); Headers hs = new Headers(); for (Header h : res.getAllHeaders()) { hs.set(h.getName(), h.getValue()); } rv.setHeaders(hs); rv.setBody(EntityUtils.toString(resEntity)); cb.accept(rv, null); } catch (Exception e) { cb.accept(null, e); } finally { EntityUtils.consumeQuietly(resEntity); } } @Override public void failed(Exception e) { cb.accept(null, e); } @Override public void cancelled() { cb.accept(null, new RuntimeException("cancelled")); } }); } }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/ApacheHttpSender.java
package ai.engageminds.sdk; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.util.function.BiConsumer; /** * default implement of HttpSender with ApacheHttpClient */ public class ApacheHttpSender implements HttpSender { private final HttpClient httpClient; private final RequestConfig reqCfg; public ApacheHttpSender() { this(HttpClients.custom() .setMaxConnPerRoute(1000) .setMaxConnTotal(10000) .build()); } public ApacheHttpSender(HttpClient httpClient) { this(httpClient, null); } public ApacheHttpSender(HttpClient httpClient, RequestConfig reqCfg) { this.httpClient = httpClient; if (reqCfg != null) { this.reqCfg = reqCfg; return; } this.reqCfg = RequestConfig.custom() .setRedirectsEnabled(false) .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setConnectionRequestTimeout(3000) .setConnectTimeout(3000) .setSocketTimeout(5000) .build(); } @Override public void send(Request req, BiConsumer<Response, Exception> cb) { HttpPost post = new HttpPost(req.getUrl()); post.setConfig(reqCfg); post.setHeader("User-Agent", UA); if (req.getCompress() != null) { post.setHeader("Content-Encoding", req.getCompress()); } post.setEntity(new ByteArrayEntity(req.getBody(), ContentType.APPLICATION_JSON)); HttpEntity resEntity = null; Response rv = new Response(); try { HttpResponse res = httpClient.execute(post); StatusLine sl = res.getStatusLine(); resEntity = res.getEntity(); rv.setStatusCode(sl.getStatusCode()); rv.setReasonPhrase(sl.getReasonPhrase()); Headers hs = new Headers(); for (Header h : res.getAllHeaders()) { hs.set(h.getName(), h.getValue()); } rv.setHeaders(hs); rv.setBody(EntityUtils.toString(resEntity)); cb.accept(rv, null); } catch (Exception e) { cb.accept(null, e); } finally { EntityUtils.consumeQuietly(resEntity); } } }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/EmSdk.java
package ai.engageminds.sdk; import ai.engageminds.sdk.dto.EventRequest; import ai.engageminds.sdk.dto.EventResponse; import lombok.Builder; import lombok.Getter; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.function.BiConsumer; import java.util.zip.GZIPOutputStream; @Getter @Builder public class EmSdk { public static final String VERSION = "1.0"; private static final String defaultServerUrl = "https://a.engageminds.ai"; private String serverUrl; private String appk; // s2s上报app key private HttpSender httpSender; private JsonProvider jsonProvider; /** * 异步单条上报 * * @param event 事件对象 */ public void track(EventRequest event) { track(event, (r, e) -> { }); } /** * 异步单条上报 * * @param event 事件对象 */ public void track(EventRequest event, BiConsumer<EventResponse, Exception> cb) { if (event.getAppk() == null) { event.setAppk(appk); } trackBatch(Collections.singletonList(event), cb); } /** * 异步批量上报 * * @param events 事件对象集合 */ public void trackBatch(List<EventRequest> events) { trackBatch(events, (r, e) -> { }); } /** * 异步批量上报 * * @param events 事件对象集合 */ public void trackBatch(List<EventRequest> events, BiConsumer<EventResponse, Exception> cb) { if (events == null || events.isEmpty()) { cb.accept(null, null); return; } for (EventRequest req : events) { if (req.getAppk() == null) { req.setAppk(appk); } } if (serverUrl == null || serverUrl.isEmpty()) { serverUrl = defaultServerUrl; } HttpSender.Request req = new HttpSender.Request(); req.setUrl(serverUrl + "/s2s/es"); try { byte[] ori = jsonProvider.format(events); ByteArrayOutputStream buf = new ByteArrayOutputStream((int) (ori.length * 0.8)); GZIPOutputStream out = new GZIPOutputStream(buf); out.write(ori); out.close(); byte[] data = buf.toByteArray(); req.setBody(data); req.setCompress("gzip"); } catch (Exception e) { cb.accept(null, e); return; } httpSender.send(req, (res, e) -> { if (e != null) { cb.accept(null, e); return; } String ct = res.getHeaders().get("content-type"); if (res.getStatusCode() != 200 || (ct == null || !ct.startsWith("application/json"))) { EventResponse rv = new EventResponse(); rv.setCode(res.getStatusCode()); rv.setMsg(res.getBody()); cb.accept(rv, null); return; } try { cb.accept(jsonProvider.parse(res.getBody().getBytes(StandardCharsets.UTF_8), EventResponse.class), null); } catch (Exception ex) { cb.accept(null, ex); } }); } }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/FastJson2Provider.java
package ai.engageminds.sdk; import com.alibaba.fastjson2.JSON; /** * default implement of JsonProvider with Fastjson */ public class FastJson2Provider implements JsonProvider { @Override public byte[] format(Object o) { return JSON.toJSONBytes(o); } @Override public <T> T parse(byte[] bs, Class<T> clazz) { return JSON.parseObject(bs, clazz); } }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/FastJsonProvider.java
package ai.engageminds.sdk; import com.alibaba.fastjson.JSON; /** * default implement of JsonProvider with Fastjson */ public class FastJsonProvider implements JsonProvider { @Override public byte[] format(Object o) { return JSON.toJSONBytes(o); } @Override public <T> T parse(byte[] bs, Class<T> clazz) { return JSON.parseObject(bs, clazz); } }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/HttpSender.java
package ai.engageminds.sdk; import lombok.Data; import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; public interface HttpSender { String UA = "em-sdk-java/" + EmSdk.VERSION; /** * send http reqeust, method POST */ void send(Request req, BiConsumer<Response, Exception> cb); @Data class Request { private String url; private String compress; private byte[] body; } @Data class Response { private int statusCode; private String reasonPhrase; private Headers headers; private String body; } class Headers { private final Map<String, String> hs = new HashMap<>(); public String get(String name) { return hs.get(name.toLowerCase()); } public void set(String name, String value) { hs.put(name.toLowerCase(), value); } } }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/JacksonProvider.java
package ai.engageminds.sdk; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; /** * default implement of JsonProvider with Jackson */ public class JacksonProvider implements JsonProvider { private final ObjectMapper mapper; public JacksonProvider() { ObjectMapper m = new ObjectMapper(); m.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); m.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); m.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); m.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); m.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true); m.setSerializationInclusion(JsonInclude.Include.NON_NULL); this.mapper = m; } public JacksonProvider(ObjectMapper mapper) { this.mapper = mapper; } @Override public byte[] format(Object o) throws Exception { return mapper.writeValueAsBytes(o); } @Override public <T> T parse(byte[] bs, Class<T> clazz) throws Exception { return mapper.readValue(bs, clazz); } }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/JsonProvider.java
package ai.engageminds.sdk; public interface JsonProvider { byte[] format(Object o) throws Exception; <T> T parse(byte[] bs, Class<T> clazz) throws Exception; }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/dto/CommonRequest.java
package ai.engageminds.sdk.dto; import ai.engageminds.sdk.EmSdk; import lombok.Data; import java.util.Map; @Data public class CommonRequest { private final int sdk = 3; // 当前SDK类型, 0:iOS,1:Android,2:JS,3:ServerJava,4:ServerGo,5:ServerPython private final String sdkv = EmSdk.VERSION; private long ts; // Client time in milliseconds private String rid; // request id private long fit; // Client first install App time, in seconds private long flt; // The first time the client opens the App, in seconds (uid file creation time) private int zo; // Time zone offset in minutes. For example, Beijing time zone Zo = 480 private String tz; // Time zone name private String session; // Session ID, UUID generated when the app is initialized private String uid; // User ID, the unique user ID generated by the SDK private String ssid; // Standardized Serviceld, generated by em-server private String gaid; // Andriod GAID private String idfa; // iOS IDFA private String idfv; // iOS IDFV private String oaid; // OAID private int dtype; // device_type, 0:unknown,1:phone,2:tablet,3:tv private String lang; // language code private int jb; // jailbreak status, 0: normal, 1: jailbreak, no transmission during normal private String bundle; // The current app package name private String make; // device maker private String brand; // device brand private String model; // device model private int os; // 操作系统, 0:iOS,1:Android,2:HarmonyOS,3:Mac,4:Windows,5:Linux private String osv; // Os version private String appk; // pubApp key private String appv; // app version private int width; // screen or placement Width private int height; // screen or placement Height private int contype; // ConnectionType private String carrier; // 运营商名称, NetworkOperatorName private String mccmnc; // 运营商mcc+mnc, NetworkOperator private String gcy; // telephony network country iso private int sco; // screen_orientation, 0:unknown,1:portrait,2:landscape private int adtk; // ad_tracking_enable, 0:No,1:Yes private int ntf; // notifications_enabled, 0:No,1:Yes private int gp; // google_play_services, 0:No,1:Yes private Map<String, Object> bps; // Custom basic values private String ip; // client IP private String ua; // client UserAgent }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/dto/Event.java
package ai.engageminds.sdk.dto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.HashMap; import java.util.List; import java.util.Map; @Builder @NoArgsConstructor @AllArgsConstructor @Data public class Event { private long ts; // Client time in milliseconds private String cdid; // media user id private String eid; // event ID private Map<String, Object> props; // event values private List<Err> err; // 返回事件错误集合 public Event setProp(String key, Object value) { if (props == null) { props = new HashMap<>(); } props.put(key, value); return this; } @Data public static class Err { private String type; // error type, private String prop; // error property name private Object value; // property value } }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/dto/EventRequest.java
package ai.engageminds.sdk.dto; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.ArrayList; import java.util.List; @EqualsAndHashCode(callSuper = true) @Data public class EventRequest extends CommonRequest { private List<Event> events; public EventRequest addEvent(Event e) { if (events == null) { events = new ArrayList<>(); } events.add(e); return this; } }
0
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk
java-sources/ai/engageminds/em-sdk-java/1.0.0/ai/engageminds/sdk/dto/EventResponse.java
package ai.engageminds.sdk.dto; import lombok.Data; import java.util.List; @Data public class EventResponse { private int code; private String msg; private List<Event> events; }
0
java-sources/ai/eto/rikai_2.12/0.1.14/org/mlflow
java-sources/ai/eto/rikai_2.12/0.1.14/org/mlflow/tracking/RiMlflowHttpCaller.java
/* * Copyright 2021 Rikai Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mlflow.tracking; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.Base64; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPatch; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.mlflow.tracking.creds.MlflowHostCreds; import org.mlflow.tracking.creds.MlflowHostCredsProvider; // Originally from mlflow client 1.21.0 class RiMlflowHttpCaller { private static final Logger logger = LoggerFactory.getLogger(RiMlflowHttpCaller.class); private static final String BASE_API_PATH = "api/2.0/preview/mlflow"; protected HttpClient httpClient; private final MlflowHostCredsProvider hostCredsProvider; private final int maxRateLimitIntervalMillis; private final int rateLimitRetrySleepInitMillis; private final int maxRetryAttempts; /** * Construct a new MlflowHttpCaller with a default configuration for request retries. */ RiMlflowHttpCaller(MlflowHostCredsProvider hostCredsProvider) { this(hostCredsProvider, 60000, 1000, 3); } /** * Construct a new MlflowHttpCaller. * * @param maxRateLimitIntervalMs The maximum amount of time, in milliseconds, to spend retrying a * single request in response to rate limiting (error code 429). * @param rateLimitRetrySleepInitMs The initial backoff delay, in milliseconds, when retrying a * request in response to rate limiting (error code 429). The * delay is increased exponentially after each rate limiting * response until the total delay incurred across all retries for * the request exceeds the specified maxRateLimitIntervalSeconds. * @param maxRetryAttempts The maximum number of times to retry a request, excluding rate limit * retries. */ RiMlflowHttpCaller(MlflowHostCredsProvider hostCredsProvider, int maxRateLimitIntervalMs, int rateLimitRetrySleepInitMs, int maxRetryAttempts) { this.hostCredsProvider = hostCredsProvider; this.maxRateLimitIntervalMillis = maxRateLimitIntervalMs; this.rateLimitRetrySleepInitMillis = rateLimitRetrySleepInitMs; this.maxRetryAttempts = maxRetryAttempts; } @VisibleForTesting RiMlflowHttpCaller(MlflowHostCredsProvider hostCredsProvider, int maxRateLimitIntervalMs, int rateLimitRetrySleepInitMs, int maxRetryAttempts, HttpClient client) { this( hostCredsProvider, maxRateLimitIntervalMs, rateLimitRetrySleepInitMs, maxRetryAttempts); this.httpClient = client; } private HttpResponse executeRequestWithRateLimitRetries(HttpRequestBase request) throws IOException { int timeLeft = maxRateLimitIntervalMillis; int sleepFor = rateLimitRetrySleepInitMillis; HttpResponse response = httpClient.execute(request); while (response.getStatusLine().getStatusCode() == 429 && timeLeft > 0) { logger.warn("Request returned with status code 429 (Rate limit exceeded). Retrying after " + sleepFor + " milliseconds. Will continue to retry 429s for up to " + timeLeft + " milliseconds."); try { Thread.sleep(sleepFor); } catch (InterruptedException e) { throw new RuntimeException(e); } timeLeft -= sleepFor; sleepFor = Math.min(timeLeft, 2 * sleepFor); response = httpClient.execute(request); } checkError(response); return response; } private HttpResponse executeRequest(HttpRequestBase request) throws IOException { HttpResponse response = null; int attemptsRemaining = this.maxRetryAttempts; while (attemptsRemaining > 0) { attemptsRemaining -= 1; try { response = executeRequestWithRateLimitRetries(request); break; } catch (MlflowHttpException e) { if (attemptsRemaining > 0 && e.getStatusCode() != 429) { logger.warn("Request returned with status code {} (Rate limit exceeded)." + " Retrying up to {} more times. Response body: {}", e.getStatusCode(), attemptsRemaining, e.getBodyMessage()); continue; } else { throw e; } } } return response; } String delete(String path, String json) { HttpDeleteWithBody request = new HttpDeleteWithBody(); return send(request, path, json); } private String send(HttpEntityEnclosingRequestBase request, String path, String json) { fillRequestSettings(request, path); request.setEntity(new StringEntity(json, StandardCharsets.UTF_8)); request.setHeader("Content-Type", "application/json"); try { HttpResponse response = executeRequest(request); String responseJson = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); logger.debug("Response: " + responseJson); return responseJson; } catch (IOException e) { throw new MlflowClientException(e); } } private void checkError(HttpResponse response) throws MlflowClientException, IOException { int statusCode = response.getStatusLine().getStatusCode(); String reasonPhrase = response.getStatusLine().getReasonPhrase(); if (isError(statusCode)) { String bodyMessage = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); if (statusCode >= 400 && statusCode <= 499) { throw new MlflowHttpException(statusCode, reasonPhrase, bodyMessage); } if (statusCode >= 500 && statusCode <= 599) { throw new MlflowHttpException(statusCode, reasonPhrase, bodyMessage); } throw new MlflowHttpException(statusCode, reasonPhrase, bodyMessage); } } private void fillRequestSettings(HttpRequestBase request, String path) { MlflowHostCreds hostCreds = hostCredsProvider.getHostCreds(); createHttpClientIfNecessary(hostCreds.shouldIgnoreTlsVerification()); String uri = hostCreds.getHost() + "/" + BASE_API_PATH + "/" + path; request.setURI(URI.create(uri)); String username = hostCreds.getUsername(); String password = hostCreds.getPassword(); String token = hostCreds.getToken(); if (username != null && password != null) { String authHeader = Base64.getEncoder() .encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8)); request.addHeader("Authorization", "Basic " + authHeader); } else if (token != null) { request.addHeader("Authorization", "Bearer " + token); } String userAgent = "mlflow-java-client"; String clientVersion = MlflowClientVersion.getClientVersion(); if (!clientVersion.isEmpty()) { userAgent += "/" + clientVersion; } request.addHeader("User-Agent", userAgent); } private boolean isError(int statusCode) { return statusCode < 200 || statusCode > 399; } private void createHttpClientIfNecessary(boolean noTlsVerify) { if (httpClient != null) { return; } HttpClientBuilder builder = HttpClientBuilder.create(); if (noTlsVerify) { try { SSLContextBuilder sslBuilder = new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslBuilder.build(), new NoopHostnameVerifier()); builder.setSSLSocketFactory(connectionFactory); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { logger.warn("Could not set noTlsVerify to true, verification will remain", e); } } this.httpClient = builder.build(); } } class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { public static final String METHOD_NAME = "DELETE"; public String getMethod() { return METHOD_NAME; } public HttpDeleteWithBody(final String uri) { super(); setURI(URI.create(uri)); } public HttpDeleteWithBody(final URI uri) { super(); setURI(uri); } public HttpDeleteWithBody() { super(); } }
0
java-sources/ai/eto/rikai_2.12/0.1.14/org/mlflow
java-sources/ai/eto/rikai_2.12/0.1.14/org/mlflow/tracking/RikaiMlflowClient.java
/* * Copyright 2021 Rikai Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mlflow.tracking; import org.mlflow.tracking.creds.*; import java.net.URI; /** * Client to an MLflow Tracking Sever. * Originally from mlflow client 1.21.0 */ public class RikaiMlflowClient extends MlflowClient { private final RiMlflowHttpCaller deleteHttpCaller; public RikaiMlflowClient(String trackingUri) { this(getHostCredsProviderFromTrackingUri(trackingUri)); } public RikaiMlflowClient(MlflowHostCredsProvider hostCredsProvider) { super(hostCredsProvider); this.deleteHttpCaller = new RiMlflowHttpCaller(hostCredsProvider); } /** * Send a DELETE to the following path, with a String-encoded JSON body. * This is mostly an internal API, but allows making lower-level or unsupported requests. * @return JSON response from the server. */ public String sendDelete(String path, String json) { return deleteHttpCaller.delete(path, json); } private static MlflowHostCredsProvider getHostCredsProviderFromTrackingUri(String trackingUri) { URI uri = URI.create(trackingUri); MlflowHostCredsProvider provider; if ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) { provider = new BasicMlflowHostCreds(trackingUri); } else if (trackingUri.equals("databricks")) { MlflowHostCredsProvider profileProvider = new DatabricksConfigHostCredsProvider(); MlflowHostCredsProvider dynamicProvider = DatabricksDynamicHostCredsProvider.createIfAvailable(); if (dynamicProvider != null) { provider = new HostCredsProviderChain(dynamicProvider, profileProvider); } else { provider = profileProvider; } } else if ("databricks".equals(uri.getScheme())) { provider = new DatabricksConfigHostCredsProvider(uri.getHost()); } else if (uri.getScheme() == null || "file".equals(uri.getScheme())) { throw new IllegalArgumentException("Java Client currently does not support" + " local tracking URIs. Please point to a Tracking Server."); } else { throw new IllegalArgumentException("Invalid tracking server uri: " + trackingUri); } return provider; } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/Allocations.java
package ai.evolv; import ai.evolv.exceptions.AscendKeyError; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class Allocations { private static final String TOUCHED = "touched"; private static final String CONFIRMED = "confirmed"; private static final String CONTAMINATED = "contaminated"; private static final Logger LOGGER = LoggerFactory.getLogger(Allocations.class); private final JsonArray allocations; private final AscendAllocationStore store; private final Audience audience = new Audience(); Allocations(JsonArray allocations, AscendAllocationStore store) { this.allocations = allocations; this.store = store; } <T> T getValueFromAllocations(String key, Class<T> cls, AscendParticipant participant) throws AscendKeyError { ArrayList<String> keyParts = new ArrayList<>(Arrays.asList(key.split("\\."))); if (keyParts.isEmpty()) { throw new AscendKeyError("Key provided was empty."); } for (JsonElement a : allocations) { JsonObject allocation = a.getAsJsonObject(); if (!audience.filter(participant.getUserAttributes(), allocation)) { try { JsonElement element = getElementFromGenome(allocation.get("genome"), keyParts); T value = new Gson().fromJson(element, cls); if (value != null) { LOGGER.debug(String.format("Found value for key '%s' in experiment %s", key, allocation.get("eid").getAsString())); markTouched(allocation); store.put(participant.getUserId(), allocations); } return value; } catch (AscendKeyError e) { LOGGER.debug(String.format("Unable to find key '%s' in experiment %s.", key, allocation.get("eid").getAsString())); continue; } } LOGGER.debug(String.format("Participant was filtered from experiment %s", allocation.get("eid").getAsString())); } throw new AscendKeyError(String.format("No value was found in any allocations for key: %s", keyParts.toString())); } private JsonElement getElementFromGenome(JsonElement genome, List<String> keyParts) throws AscendKeyError { JsonElement element = genome; if (element == null) { throw new AscendKeyError("Allocation genome was empty."); } for (String part : keyParts) { JsonObject object = element.getAsJsonObject(); element = object.get(part); if (element == null) { throw new AscendKeyError("Could not find value for key: " + keyParts.toString()); } } return element; } /** * Reconciles the previous allocations with any new allocations. * * <p> * Check the current allocations for any allocations that belong to experiments * in the previous allocations. If there are, keep the previous allocations. * If there are any live experiments that are not in the previous allocations * add the new allocation to the allocations list. * </p> * * @param previousAllocations the stored allocations * @param currentAllocations the allocations recently fetched * @return the reconcile allocations */ static JsonArray reconcileAllocations(JsonArray previousAllocations, JsonArray currentAllocations) { JsonArray allocations = new JsonArray(); for (JsonElement ca : currentAllocations) { JsonObject currentAllocation = ca.getAsJsonObject(); String currentEid = currentAllocation.get("eid").toString(); boolean previousFound = false; for (JsonElement pa : previousAllocations) { JsonObject previousAllocation = pa.getAsJsonObject(); String previousEid = previousAllocation.get("eid").toString(); if (previousEid.equals(currentEid)) { allocations.add(pa.getAsJsonObject()); previousFound = true; } } if (!previousFound) { allocations.add(ca.getAsJsonObject()); } } return allocations; } Set<String> getActiveExperiments() { Set<String> activeExperiments = new HashSet<>(); for (JsonElement a : allocations) { JsonObject allocation = a.getAsJsonObject(); activeExperiments.add(allocation.get("eid").getAsString()); } return activeExperiments; } static JsonObject markTouched(JsonObject allocation) { allocation.addProperty(TOUCHED, true); return allocation; } static boolean isTouched(JsonObject allocation) { return allocation.has(TOUCHED) && allocation.get(TOUCHED).getAsBoolean(); } static JsonObject markConfirmed(JsonObject allocation) { allocation.addProperty(CONFIRMED, true); return allocation; } static boolean isConfirmed(JsonObject allocation) { return allocation.has(CONFIRMED) && allocation.get(CONFIRMED).getAsBoolean(); } static JsonObject markContaminated(JsonObject allocation) { allocation.addProperty(CONTAMINATED, true); return allocation; } static boolean isContaminated(JsonObject allocation) { return allocation.has(CONTAMINATED) && allocation.get(CONTAMINATED).getAsBoolean(); } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/Allocator.java
package ai.evolv; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import com.google.gson.JsonArray; import com.google.gson.JsonParser; import java.net.URI; import java.net.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class Allocator { private static final Logger LOGGER = LoggerFactory.getLogger(Allocator.class); enum AllocationStatus { FETCHING, RETRIEVED, FAILED } private final ExecutionQueue executionQueue; private final AscendAllocationStore store; private final AscendConfig config; private final AscendParticipant participant; private final EventEmitter eventEmitter; private final HttpClient httpClient; private boolean confirmationSandbagged = false; private boolean contaminationSandbagged = false; private AllocationStatus allocationStatus; Allocator(AscendConfig config, AscendParticipant participant) { this.executionQueue = config.getExecutionQueue(); this.store = config.getAscendAllocationStore(); this.config = config; this.participant = participant; this.httpClient = config.getHttpClient(); this.allocationStatus = AllocationStatus.FETCHING; this.eventEmitter = new EventEmitter(config, participant, this.store); } AllocationStatus getAllocationStatus() { return allocationStatus; } void sandBagConfirmation() { confirmationSandbagged = true; } void sandBagContamination() { contaminationSandbagged = true; } String createAllocationsUrl() { try { String path = String.format("//%s/%s/%s/allocations", config.getDomain(), config.getVersion(), config.getEnvironmentId()); String queryString = String.format("uid=%s&sid=%s", participant.getUserId(), participant.getSessionId()); URI uri = new URI(config.getHttpScheme(), null, path, queryString, null); URL url = uri.toURL(); return url.toString(); } catch (Exception e) { LOGGER.error("There was an issue creating the allocations url.", e); return ""; } } ListenableFuture<JsonArray> fetchAllocations() { ListenableFuture<String> responseFuture = httpClient.get(createAllocationsUrl()); SettableFuture<JsonArray> allocationsFuture = SettableFuture.create(); responseFuture.addListener(new Runnable() { @Override public void run() { try { JsonParser parser = new JsonParser(); JsonArray allocations = parser.parse(responseFuture.get()).getAsJsonArray(); JsonArray previousAllocations = store.get(participant.getUserId()); if (allocationsNotEmpty(previousAllocations)) { allocations = Allocations.reconcileAllocations(previousAllocations, allocations); } store.put(participant.getUserId(), allocations); allocationStatus = AllocationStatus.RETRIEVED; allocationsFuture.set(allocations); executionQueue.executeAllWithValuesFromAllocations(allocations, eventEmitter, confirmationSandbagged, contaminationSandbagged); } catch (Exception e) { LOGGER.warn("There was a failure while retrieving the allocations.", e); allocationsFuture.set(resolveAllocationFailure()); } } }, MoreExecutors.directExecutor()); return allocationsFuture; } JsonArray resolveAllocationFailure() { JsonArray previousAllocations = store.get(participant.getUserId()); if (allocationsNotEmpty(previousAllocations)) { LOGGER.debug("Falling back to participant's previous allocation."); allocationStatus = AllocationStatus.RETRIEVED; executionQueue.executeAllWithValuesFromAllocations(previousAllocations, eventEmitter, confirmationSandbagged, contaminationSandbagged); } else { LOGGER.debug("Falling back to the supplied defaults."); allocationStatus = AllocationStatus.FAILED; executionQueue.executeAllWithValuesFromDefaults(); previousAllocations = new JsonArray(); } return previousAllocations; } static boolean allocationsNotEmpty(JsonArray allocations) { return allocations != null && allocations.size() > 0; } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/AscendAction.java
package ai.evolv; public interface AscendAction<T> { /** * Applies a given value to a set of instructions. * @param value any value that was requested */ void apply(T value); }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/AscendAllocationStore.java
package ai.evolv; import com.google.gson.JsonArray; public interface AscendAllocationStore { /** * Retrieves a JsonArray. * <p> * Retrieves a JsonArray that represents the participant's allocations. * If there are no stored allocations, should return an empty JsonArray. * </p> * @param uid the participant's unique id * @return an allocation if one exists else an empty JsonArray */ JsonArray get(String uid); /** * Stores a JsonArray. * <p> * Stores the given JsonArray. * </p> * @param uid the participant's unique id * @param allocations the participant's allocations */ void put(String uid, JsonArray allocations); }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/AscendClient.java
package ai.evolv; public interface AscendClient { /** * Retrieves a value from the participant's allocation, returns a default upon error. * <p> * Given a unique key this method will retrieve the key's associated value. A * default value can also be specified in case any errors occur during the values * retrieval. If the allocation call times out or fails the default value is * always returned. This method is blocking, it will wait till the allocation * is available and then return. * </p> * @param key a unique key identifying a specific value in the participants * allocation * @param defaultValue a default value to return upon error * @param <T> type of value to be returned * @return a value associated with the given key */ <T> T get(String key, T defaultValue); /** * Retrieves a value from Ascend asynchronously and applies some custom action. * <p> * This method is non blocking. It will preform the programmed action once * the allocation is available. If there is already of stored allocation * it will immediately apply the value retrieved and then when the new * allocation returns it will reapply the new changes if the experiment * has changed. * </p> * @param key a unique key identifying a specific value in the participants * allocation * @param defaultValue a default value to return upon error * @param function a handler that is invoked when the allocation is updated * @param <T> type of value to be returned */ <T> void subscribe(String key, T defaultValue, AscendAction<T> function); /** * Emits a generic event to be recorded by Ascend. * <p> * Sends an event to Ascend to be recorded and reported upon. Also records * a generic score value to be associated with the event. * </p> * @param key the identifier of the event * @param score a score to be associated with the event */ void emitEvent(String key, Double score); /** * Emits a generic event to be recorded by Ascend. * <p> * Sends an event to Ascend to be recorded and reported upon. * </p> * @param key the identifier of the event */ void emitEvent(String key); /** * Sends a confirmed event to Ascend. * <p> * Method produces a confirmed event which confirms the participant's * allocation. Method will not do anything in the event that the allocation * timed out or failed. * </p> */ void confirm(); /** * Sends a contamination event to Ascend. * <p> * Method produces a contamination event which will contaminate the * participant's allocation. Method will not do anything in the event * that the allocation timed out or failed. * </p> */ void contaminate(); }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/AscendClientFactory.java
package ai.evolv; import com.google.common.util.concurrent.ListenableFuture; import com.google.gson.JsonArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AscendClientFactory { private static final Logger LOGGER = LoggerFactory.getLogger(AscendClientFactory.class); /** * Creates instances of the AscendClient. * * @param config general configurations for the SDK * @return an instance of AscendClient */ public static AscendClient init(AscendConfig config) { LOGGER.debug("Initializing Ascend Client."); AscendParticipant participant = AscendParticipant.builder().build(); return AscendClientFactory.createClient(config, participant); } /** * Creates instances of the AscendClient. * * @param config general configurations for the SDK * @param participant the participant for the initialized client * @return an instance of AscendClient */ public static AscendClient init(AscendConfig config, AscendParticipant participant) { LOGGER.debug("Initializing Ascend Client."); return AscendClientFactory.createClient(config, participant); } private static AscendClient createClient(AscendConfig config, AscendParticipant participant) { AscendAllocationStore store = config.getAscendAllocationStore(); JsonArray previousAllocations = store.get(participant.getUserId()); Allocator allocator = new Allocator(config, participant); // fetch and reconcile allocations asynchronously ListenableFuture<JsonArray> futureAllocations = allocator.fetchAllocations(); return new AscendClientImpl(config, new EventEmitter(config, participant, store), futureAllocations, allocator, Allocator.allocationsNotEmpty(previousAllocations), participant); } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/AscendClientImpl.java
package ai.evolv; import ai.evolv.exceptions.AscendKeyError; import ai.evolv.generics.GenericClass; import com.google.common.util.concurrent.ListenableFuture; import com.google.gson.JsonArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class AscendClientImpl implements AscendClient { private static final Logger LOGGER = LoggerFactory.getLogger(AscendClientImpl.class); private final EventEmitter eventEmitter; private final ListenableFuture<JsonArray> futureAllocations; private final ExecutionQueue executionQueue; private final Allocator allocator; private final AscendAllocationStore store; private final boolean previousAllocations; private final AscendParticipant participant; AscendClientImpl(AscendConfig config, EventEmitter emitter, ListenableFuture<JsonArray> futureAllocations, Allocator allocator, boolean previousAllocations, AscendParticipant participant) { this.store = config.getAscendAllocationStore(); this.executionQueue = config.getExecutionQueue(); this.eventEmitter = emitter; this.futureAllocations = futureAllocations; this.allocator = allocator; this.previousAllocations = previousAllocations; this.participant = participant; } @Override public <T> T get(String key, T defaultValue) { try { if (futureAllocations == null) { return defaultValue; } // this is blocking JsonArray allocations = futureAllocations.get(); if (!Allocator.allocationsNotEmpty(allocations)) { return defaultValue; } GenericClass<T> cls = new GenericClass(defaultValue.getClass()); T value = new Allocations(allocations, store).getValueFromAllocations(key, cls.getMyType(), participant); if (value == null) { throw new AscendKeyError("Got null when retrieving key from allocations."); } return value; } catch (AscendKeyError e) { LOGGER.debug("Unable to retrieve the treatment. Returning " + "the default.", e); return defaultValue; } catch (Exception e) { LOGGER.error("An error occurred while retrieving the treatment. Returning " + "the default.", e); return defaultValue; } } @Override public <T> void subscribe(String key, T defaultValue, AscendAction<T> function) { Execution execution = new Execution<>(key, defaultValue, function, participant, store); if (previousAllocations) { try { JsonArray allocations = store.get(participant.getUserId()); execution.executeWithAllocation(allocations); } catch (AscendKeyError e) { LOGGER.debug("Unable to retrieve the value of %s from the allocation.", execution.getKey()); execution.executeWithDefault(); } catch (Exception e) { LOGGER.error("There was an error when applying the stored treatment.", e); } } Allocator.AllocationStatus allocationStatus = allocator.getAllocationStatus(); if (allocationStatus == Allocator.AllocationStatus.FETCHING) { executionQueue.enqueue(execution); return; } else if (allocationStatus == Allocator.AllocationStatus.RETRIEVED) { try { JsonArray allocations = store.get(participant.getUserId()); execution.executeWithAllocation(allocations); return; } catch (AscendKeyError e) { LOGGER.debug(String.format("Unable to retrieve" + " the value of %s from the allocation.", execution.getKey()), e); } catch (Exception e) { LOGGER.error("There was an error applying the subscribed method.", e); } } execution.executeWithDefault(); } @Override public void emitEvent(String key, Double score) { this.eventEmitter.emit(key, score); } @Override public void emitEvent(String key) { this.eventEmitter.emit(key); } @Override public void confirm() { Allocator.AllocationStatus allocationStatus = allocator.getAllocationStatus(); if (allocationStatus == Allocator.AllocationStatus.FETCHING) { allocator.sandBagConfirmation(); } else if (allocationStatus == Allocator.AllocationStatus.RETRIEVED) { eventEmitter.confirm(store.get(participant.getUserId())); } } @Override public void contaminate() { Allocator.AllocationStatus allocationStatus = allocator.getAllocationStatus(); if (allocationStatus == Allocator.AllocationStatus.FETCHING) { allocator.sandBagContamination(); } else if (allocationStatus == Allocator.AllocationStatus.RETRIEVED) { eventEmitter.contaminate(store.get(participant.getUserId())); } } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/AscendConfig.java
package ai.evolv; public class AscendConfig { static final String DEFAULT_HTTP_SCHEME = "https"; static final String DEFAULT_DOMAIN = "participants.evolv.ai"; static final String DEFAULT_API_VERSION = "v1"; private static final int DEFAULT_ALLOCATION_STORE_SIZE = 1000; private final String httpScheme; private final String domain; private final String version; private final String environmentId; private final AscendAllocationStore ascendAllocationStore; private final HttpClient httpClient; private final ExecutionQueue executionQueue; private AscendConfig(String httpScheme, String domain, String version, String environmentId, AscendAllocationStore ascendAllocationStore, HttpClient httpClient) { this.httpScheme = httpScheme; this.domain = domain; this.version = version; this.environmentId = environmentId; this.ascendAllocationStore = ascendAllocationStore; this.httpClient = httpClient; this.executionQueue = new ExecutionQueue(); } public static Builder builder(String environmentId, HttpClient httpClient) { return new Builder(environmentId, httpClient); } String getHttpScheme() { return httpScheme; } String getDomain() { return domain; } String getVersion() { return version; } String getEnvironmentId() { return environmentId; } AscendAllocationStore getAscendAllocationStore() { return ascendAllocationStore; } HttpClient getHttpClient() { return this.httpClient; } ExecutionQueue getExecutionQueue() { return this.executionQueue; } public static class Builder { private int allocationStoreSize = DEFAULT_ALLOCATION_STORE_SIZE; private String httpScheme = DEFAULT_HTTP_SCHEME; private String domain = DEFAULT_DOMAIN; private String version = DEFAULT_API_VERSION; private AscendAllocationStore allocationStore; private String environmentId; private HttpClient httpClient; /** * Responsible for creating an instance of AscendClientImpl. * <p> * Builds an instance of the AscendClientImpl. The only required parameter is the * customer's environment id. * </p> * @param environmentId unique id representing a customer's environment */ Builder(String environmentId, HttpClient httpClient) { this.environmentId = environmentId; this.httpClient = httpClient; } /** * Sets the domain of the underlying ascendParticipant api. * @param domain the domain of the ascendParticipant api * @return AscendClientBuilder class */ public Builder setDomain(String domain) { this.domain = domain; return this; } /** * Version of the underlying ascendParticipant api. * @param version representation of the required ascendParticipant api version * @return AscendClientBuilder class */ public Builder setVersion(String version) { this.version = version; return this; } /** * Sets up a custom AscendAllocationStore. Store needs to implement the * AscendAllocationStore interface. * @param allocationStore a custom built allocation store * @return AscendClientBuilder class */ public Builder setAscendAllocationStore(AscendAllocationStore allocationStore) { this.allocationStore = allocationStore; return this; } /** * Tells the SDK to use either http or https. * @param scheme either http or https * @return AscendClientBuilder class */ public Builder setHttpScheme(String scheme) { this.httpScheme = scheme; return this; } /** * Sets the DefaultAllocationStores size. * @param size number of entries allowed in the default allocation store * @return AscendClientBuilder class */ public Builder setDefaultAllocationStoreSize(int size) { this.allocationStoreSize = size; return this; } /** * Builds an instance of AscendClientImpl. * @return an AscendClientImpl instance */ public AscendConfig build() { if (allocationStore == null) { allocationStore = new DefaultAllocationStore(allocationStoreSize); } return new AscendConfig(httpScheme, domain, version, environmentId, allocationStore, httpClient); } } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/AscendParticipant.java
package ai.evolv; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class AscendParticipant { private final String sessionId; private String userId; private Map<String, String> userAttributes; private AscendParticipant(String userId, String sessionId, Map<String, String> userAttributes) { this.userId = userId; this.sessionId = sessionId; this.userAttributes = userAttributes; } public static Builder builder() { return new Builder(); } String getUserId() { return userId; } String getSessionId() { return sessionId; } Map<String, String> getUserAttributes() { return userAttributes; } void setUserId(String userId) { this.userId = userId; } public static class Builder { private String userId = UUID.randomUUID().toString(); private String sessionId = UUID.randomUUID().toString(); private Map<String, String> userAttributes = new HashMap<>(); /** * A unique key representing the participant. * @param userId a unique key * @return this instance of the participant */ public Builder setUserId(String userId) { this.userId = userId; return this; } /** * A unique key representing the participant's session. * @param sessionId a unique key * @return this instance of the participant */ public Builder setSessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Sets the users attributes which can be used to filter users upon. * @param userAttributes a map representing specific attributes that * describe the participant * @return this instance of the participant */ public Builder setUserAttributes(Map<String, String> userAttributes) { this.userAttributes = userAttributes; return this; } /** * Builds the AscendParticipant instance. * @return an AscendParticipant instance. */ public AscendParticipant build() { userAttributes.put("uid", userId); userAttributes.put("sid", sessionId); return new AscendParticipant(userId, sessionId, userAttributes); } } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/Audience.java
package ai.evolv; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.HashMap; import java.util.Map; public class Audience { @FunctionalInterface interface Function<A, B> { boolean apply(A one, B two); } private Map<String, Function> operators = createOperatorsMap(); private Map<String, Function> createOperatorsMap() { Map<String, Function> operatorsMap = new HashMap<>(); operatorsMap.put("exists", (object, a) -> ((Map<String, String>) object) .containsKey(((JsonElement) a).getAsString())); operatorsMap.put("kv_contains", (object, params) -> { String storedValue = ((Map<String, String>) object).get( ((JsonArray) params).get(0).getAsString()); if (storedValue == null) { return false; } return storedValue.contains(((JsonArray) params).get(1).getAsString()); }); operatorsMap.put("kv_not_contains", (object, params) -> { String storedValue = ((Map<String, String>) object).get( ((JsonArray) params).get(0).getAsString()); if (storedValue == null) { return false; } return !storedValue.contains(((JsonArray) params).get(1).getAsString()); }); operatorsMap.put("kv_equal", (object, params) -> { String storedValue = ((Map<String, String>) object).get( ((JsonArray) params).get(0).getAsString()); if (storedValue == null) { return false; } return storedValue.equals(((JsonArray) params).get(1).getAsString()); }); operatorsMap.put("kv_not_equal", (object, params) -> { String storedValue = ((Map<String, String>) object).get( ((JsonArray) params).get(0).getAsString()); if (storedValue == null) { return false; } return !storedValue.equals(((JsonArray) params).get(1).getAsString()); }); return operatorsMap; } private boolean evaluateAudienceFilter(Map<String, String> userAttributes, JsonObject rule) { return operators.get(rule.get("operator").getAsString()).apply(userAttributes, rule.get("value")); } private boolean evaluateAudienceRule(Map<String, String> userAttributes, JsonObject audienceQuery, JsonObject rule) { if (rule.has("combinator")) { return evaluateAudienceQuery(userAttributes, rule); } return evaluateAudienceFilter(userAttributes, rule); } private boolean evaluateAudienceQuery(Map<String, String> userAttributes, JsonObject audienceQuery) { JsonElement rules = audienceQuery.get("rules"); if (rules == null) { return true; } for (JsonElement r : rules.getAsJsonArray()) { boolean passed = evaluateAudienceRule(userAttributes, audienceQuery, r.getAsJsonObject()); String combinator = audienceQuery.get("combinator").getAsString(); if (passed && combinator.equals("or")) { return true; } if (!passed && combinator.equals("and")) { return false; } } return audienceQuery.get("combinator").getAsString().equals("and"); } /** * Determines whether on not to filter the user based upon the supplied user * attributes and allocation. * @param userAttributes map representing attributes that represent the participant * @param allocation allocation containing the participant's treatment(s) * @return true if participant should be filters, false if not */ public boolean filter(Map<String, String> userAttributes, JsonObject allocation) { JsonElement excluded = allocation.get("excluded"); if (excluded != null && excluded.getAsBoolean()) { return true; } JsonElement audienceQuery = allocation.get("audience_query"); if (userAttributes == null || userAttributes.isEmpty() || audienceQuery == null || audienceQuery.isJsonNull()) { return false; } return !evaluateAudienceQuery(userAttributes, audienceQuery.getAsJsonObject()); } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/DefaultAllocationStore.java
package ai.evolv; import com.google.gson.JsonArray; public class DefaultAllocationStore implements AscendAllocationStore { private LruCache cache; DefaultAllocationStore(int size) { this.cache = new LruCache(size); } @Override public JsonArray get(String uid) { return cache.getEntry(uid); } @Override public void put(String uid, JsonArray allocations) { cache.putEntry(uid, allocations); } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/EventEmitter.java
package ai.evolv; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.net.URI; import java.net.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class EventEmitter { private static final Logger LOGGER = LoggerFactory.getLogger(ExecutionQueue.class); static final String CONFIRM_KEY = "confirmation"; static final String CONTAMINATE_KEY = "contamination"; private final HttpClient httpClient; private final AscendConfig config; private final AscendParticipant participant; private final AscendAllocationStore store; private final Audience audience = new Audience(); EventEmitter(AscendConfig config, AscendParticipant participant, AscendAllocationStore store) { this.httpClient = config.getHttpClient(); this.config = config; this.participant = participant; this.store = store; } void emit(String key) { String url = getEventUrl(key, 1.0); makeEventRequest(url); } void emit(String key, Double score) { String url = getEventUrl(key, score); makeEventRequest(url); } void confirm(JsonArray allocations) { sendAllocationEvents(CONFIRM_KEY, allocations); } void contaminate(JsonArray allocations) { sendAllocationEvents(CONTAMINATE_KEY, allocations); } void sendAllocationEvents(String key, JsonArray allocations) { for (JsonElement a : allocations) { JsonObject allocation = a.getAsJsonObject(); if (!audience.filter(participant.getUserAttributes(), allocation) && Allocations.isTouched(allocation) && !Allocations.isConfirmed(allocation) && !Allocations.isContaminated(allocation)) { String experimentId = allocation.get("eid").getAsString(); String candidateId = allocation.get("cid").getAsString(); String url = getEventUrl(key, experimentId, candidateId); makeEventRequest(url); if (key.equals(CONFIRM_KEY)) { Allocations.markConfirmed(allocation); } else if (key.equals(CONTAMINATE_KEY)) { Allocations.markContaminated(allocation); } continue; } LOGGER.debug(String.format("%s event filtered for experiment %s.", key, allocation.get("eid").getAsString())); } store.put(this.participant.getUserId(), allocations); } String getEventUrl(String type, Double score) { try { String path = String.format("//%s/%s/%s/events", config.getDomain(), config.getVersion(), config.getEnvironmentId()); String queryString = String.format("uid=%s&sid=%s&type=%s&score=%s", participant.getUserId(), participant.getSessionId(), type, score.toString()); URI uri = new URI(config.getHttpScheme(), null, path, queryString, null); URL url = uri.toURL(); return url.toString(); } catch (Exception e) { LOGGER.error("There was an error while creating the events url.", e); return null; } } String getEventUrl(String type, String experimentId, String candidateId) { try { String path = String.format("//%s/%s/%s/events", config.getDomain(), config.getVersion(), config.getEnvironmentId()); String queryString = String.format("uid=%s&sid=%s&eid=%s&cid=%s&type=%s", participant.getUserId(), participant.getSessionId(), experimentId, candidateId, type); URI uri = new URI(config.getHttpScheme(), null, path, queryString, null); URL url = uri.toURL(); return url.toString(); } catch (Exception e) { LOGGER.error("There was an error while creating the events url.", e); return null; } } private void makeEventRequest(String url) { if (url != null) { try { httpClient.get(url); } catch (Exception e) { LOGGER.error(String.format("There was an exception while making" + " an event request with %s", url), e); } } else { LOGGER.debug("The event url was null, skipping event request."); } } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/Execution.java
package ai.evolv; import ai.evolv.exceptions.AscendKeyError; import ai.evolv.generics.GenericClass; import com.google.gson.JsonArray; import java.util.HashSet; import java.util.Set; class Execution<T> { private final String key; private final T defaultValue; private final AscendAction function; private final AscendParticipant participant; private final AscendAllocationStore store; private Set<String> alreadyExecuted = new HashSet<>(); Execution(String key, T defaultValue, AscendAction<T> function, AscendParticipant participant, AscendAllocationStore store) { this.key = key; this.defaultValue = defaultValue; this.function = function; this.participant = participant; this.store = store; } String getKey() { return key; } void executeWithAllocation(JsonArray rawAllocations) throws AscendKeyError { GenericClass<T> cls = new GenericClass(defaultValue.getClass()); Allocations allocations = new Allocations(rawAllocations, store); T value = allocations.getValueFromAllocations(key, cls.getMyType(), participant); if (value == null) { throw new AscendKeyError("Got null when retrieving key from allocations."); } Set<String> activeExperiments = allocations.getActiveExperiments(); if (alreadyExecuted.isEmpty() || !alreadyExecuted.equals(activeExperiments)) { // there was a change to the allocations after reconciliation, apply changes function.apply(value); } alreadyExecuted = activeExperiments; } void executeWithDefault() { function.apply(defaultValue); } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/ExecutionQueue.java
package ai.evolv; import ai.evolv.exceptions.AscendKeyError; import com.google.gson.JsonArray; import java.util.concurrent.ConcurrentLinkedQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class ExecutionQueue { private static final Logger LOGGER = LoggerFactory.getLogger(ExecutionQueue.class); private final ConcurrentLinkedQueue<Execution> queue; ExecutionQueue() { this.queue = new ConcurrentLinkedQueue<>(); } void enqueue(Execution execution) { this.queue.add(execution); } void executeAllWithValuesFromAllocations(JsonArray allocations, EventEmitter eventEmitter, boolean confirmationSandbagged, boolean contaminationSandbagged) { while (!queue.isEmpty()) { Execution execution = queue.remove(); try { execution.executeWithAllocation(allocations); } catch (AscendKeyError e) { LOGGER.debug(String.format("There was an error retrieving" + " the value of %s from the allocation.", execution.getKey()), e); execution.executeWithDefault(); } catch (Exception e) { LOGGER.error("There was an issue while performing one of" + " the stored actions.", e); } } if (confirmationSandbagged) { eventEmitter.confirm(allocations); } if (contaminationSandbagged) { eventEmitter.contaminate(allocations); } } void executeAllWithValuesFromDefaults() { while (!queue.isEmpty()) { Execution execution = queue.remove(); execution.executeWithDefault(); } } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/HttpClient.java
package ai.evolv; import com.google.common.util.concurrent.ListenableFuture; public interface HttpClient { /** * Performs a GET request using the provided url. * <p> * This call is asynchronous, the request is sent and a completable future * is returned. The future is completed when the result of the request returns. * The timeout of the request is determined in the implementation of the * HttpClient. * </p> * @param url a valid url representing a call to the Participant API. * @return a response future */ ListenableFuture<String> get(String url); }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/LruCache.java
package ai.evolv; import com.google.gson.JsonArray; class LruCache { private MaxSizeHashMap<String, JsonArray> cache; LruCache(int cacheSize) { this.cache = new MaxSizeHashMap<>(cacheSize); } JsonArray getEntry(String key) { if (cache.containsKey(key)) { JsonArray entry = cache.get(key); cache.remove(key); cache.put(key, entry); return entry; } return new JsonArray(); } void putEntry(String key, JsonArray value) { if (cache.containsKey(key)) { cache.remove(key); cache.put(key, value); } else { cache.put(key, value); } } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/MaxSizeHashMap.java
package ai.evolv; import java.util.LinkedHashMap; import java.util.Map; public class MaxSizeHashMap<K, V> extends LinkedHashMap<K, V> { private final int maxSize; public MaxSizeHashMap(int maxSize) { this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > maxSize; } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/exceptions/AscendKeyError.java
package ai.evolv.exceptions; public class AscendKeyError extends Exception { public AscendKeyError(String errorMessage) { super(errorMessage); } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/generics/GenericClass.java
package ai.evolv.generics; public class GenericClass<T> { private final Class<T> type; public GenericClass(Class<T> type) { this.type = type; } public Class<T> getMyType() { return this.type; } }
0
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv
java-sources/ai/evolv/ascend-android-sdk/0.6.1/ai/evolv/httpclients/OkHttpClient.java
package ai.evolv.httpclients; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import ai.evolv.HttpClient; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.ConnectionPool; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; public class OkHttpClient implements HttpClient { private final okhttp3.OkHttpClient httpClient; /** * Initializes the OhHttp# httpClient. * <p> * Note: Default timeout is 1 second * </p> */ public OkHttpClient() { this.httpClient = new okhttp3.OkHttpClient.Builder() .callTimeout(1, TimeUnit.SECONDS) .connectionPool(new ConnectionPool(3, 1000, TimeUnit.MILLISECONDS)) .build(); } /** * Initializes the OhHttp# httpClient. * * @param timeUnit Specify the unit of the timeout value. * @param timeout Specify a request timeout for the httpClient. */ public OkHttpClient(TimeUnit timeUnit, long timeout) { this.httpClient = new okhttp3.OkHttpClient.Builder() .callTimeout(timeout, timeUnit) .connectionPool(new ConnectionPool(3, 1000, TimeUnit.MILLISECONDS)) .build(); } /** * Initializes the OhHttp# httpClient. * * @param httpClient An instance of okhttp3.OkHttpClient for Ascend to use. */ public OkHttpClient(okhttp3.OkHttpClient httpClient) { this.httpClient = httpClient; } /** * Performs a GET request with the given url using the httpClient from * okhttp3. * @param url a valid url representing a call to the Participant API. * @return a Listenable future instance containing a response from * the API */ public ListenableFuture<String> get(String url) { return getStringSettableFuture(url, httpClient); } private static SettableFuture<String> getStringSettableFuture( String url, okhttp3.OkHttpClient httpClient) { SettableFuture<String> responseFuture = SettableFuture.create(); final Request request = new Request.Builder() .url(url) .build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { responseFuture.setException(e); } @Override public void onResponse(Call call, Response response) { String body = ""; try (ResponseBody responseBody = response.body()) { if (responseBody != null) { body = responseBody.string(); } if (!response.isSuccessful()) { throw new IOException(String.format("Unexpected response " + "when making GET request: %s using url: %s with body: %s", response, request.url(), body)); } responseFuture.set(body); } catch (Exception e) { responseFuture.setException(e); } } }); return responseFuture; } }
0
java-sources/ai/evolv/ascend-sdk/0.7.1/ai
java-sources/ai/evolv/ascend-sdk/0.7.1/ai/evolv/Allocations.java
package ai.evolv; import ai.evolv.exceptions.AscendKeyError; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class Allocations { private static final String TOUCHED = "touched"; private static final String CONFIRMED = "confirmed"; private static final String CONTAMINATED = "contaminated"; private static final Logger LOGGER = LoggerFactory.getLogger(Allocations.class); private final JsonArray allocations; private final AscendAllocationStore store; private final Audience audience = new Audience(); Allocations(JsonArray allocations, AscendAllocationStore store) { this.allocations = allocations; this.store = store; } <T> T getValueFromAllocations(String key, Class<T> cls, AscendParticipant participant) throws AscendKeyError { ArrayList<String> keyParts = new ArrayList<>(Arrays.asList(key.split("\\."))); if (keyParts.isEmpty()) { throw new AscendKeyError("Key provided was empty."); } for (JsonElement a : allocations) { JsonObject allocation = a.getAsJsonObject(); if (!audience.filter(participant.getUserAttributes(), allocation)) { try { JsonElement element = getElementFromGenome(allocation.get("genome"), keyParts); T value = new Gson().fromJson(element, cls); if (value != null) { LOGGER.debug(String.format("Found value for key '%s' in experiment %s", key, allocation.get("eid").getAsString())); markTouched(allocation); store.put(participant.getUserId(), allocations); } return value; } catch (AscendKeyError e) { LOGGER.debug(String.format("Unable to find key '%s' in experiment %s.", key, allocation.get("eid").getAsString())); continue; } } LOGGER.debug(String.format("Participant was filtered from experiment %s", allocation.get("eid").getAsString())); } throw new AscendKeyError(String.format("No value was found in any allocations for key: %s", keyParts.toString())); } private JsonElement getElementFromGenome(JsonElement genome, List<String> keyParts) throws AscendKeyError { JsonElement element = genome; if (element == null) { throw new AscendKeyError("Allocation genome was empty."); } for (String part : keyParts) { JsonObject object = element.getAsJsonObject(); element = object.get(part); if (element == null) { throw new AscendKeyError("Could not find value for key: " + keyParts.toString()); } } return element; } /** * Reconciles the previous allocations with any new allocations. * * <p> * Check the current allocations for any allocations that belong to experiments * in the previous allocations. If there are, keep the previous allocations. * If there are any live experiments that are not in the previous allocations * add the new allocation to the allocations list. * </p> * * @param previousAllocations the stored allocations * @param currentAllocations the allocations recently fetched * @return the reconcile allocations */ static JsonArray reconcileAllocations(JsonArray previousAllocations, JsonArray currentAllocations) { JsonArray allocations = new JsonArray(); for (JsonElement ca : currentAllocations) { JsonObject currentAllocation = ca.getAsJsonObject(); String currentEid = currentAllocation.get("eid").toString(); boolean previousFound = false; for (JsonElement pa : previousAllocations) { JsonObject previousAllocation = pa.getAsJsonObject(); String previousEid = previousAllocation.get("eid").toString(); if (previousEid.equals(currentEid)) { allocations.add(pa.getAsJsonObject()); previousFound = true; } } if (!previousFound) { allocations.add(ca.getAsJsonObject()); } } return allocations; } Set<String> getActiveExperiments() { Set<String> activeExperiments = new HashSet<>(); for (JsonElement a : allocations) { JsonObject allocation = a.getAsJsonObject(); activeExperiments.add(allocation.get("eid").getAsString()); } return activeExperiments; } static JsonObject markTouched(JsonObject allocation) { allocation.addProperty(TOUCHED, true); return allocation; } static boolean isTouched(JsonObject allocation) { return allocation.has(TOUCHED) && allocation.get(TOUCHED).getAsBoolean(); } static JsonObject markConfirmed(JsonObject allocation) { allocation.addProperty(CONFIRMED, true); return allocation; } static boolean isConfirmed(JsonObject allocation) { return allocation.has(CONFIRMED) && allocation.get(CONFIRMED).getAsBoolean(); } static JsonObject markContaminated(JsonObject allocation) { allocation.addProperty(CONTAMINATED, true); return allocation; } static boolean isContaminated(JsonObject allocation) { return allocation.has(CONTAMINATED) && allocation.get(CONTAMINATED).getAsBoolean(); } }
0
java-sources/ai/evolv/ascend-sdk/0.7.1/ai
java-sources/ai/evolv/ascend-sdk/0.7.1/ai/evolv/Allocator.java
package ai.evolv; import com.google.gson.JsonArray; import com.google.gson.JsonParser; import java.net.URI; import java.net.URL; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class Allocator { private static final Logger LOGGER = LoggerFactory.getLogger(Allocator.class); enum AllocationStatus { FETCHING, RETRIEVED, FAILED } private final ExecutionQueue executionQueue; private final AscendAllocationStore store; private final AscendConfig config; private final AscendParticipant participant; private final EventEmitter eventEmitter; private final HttpClient httpClient; private boolean confirmationSandbagged = false; private boolean contaminationSandbagged = false; private AllocationStatus allocationStatus; Allocator(AscendConfig config, AscendParticipant participant) { this.executionQueue = config.getExecutionQueue(); this.store = config.getAscendAllocationStore(); this.config = config; this.participant = participant; this.httpClient = config.getHttpClient(); this.allocationStatus = AllocationStatus.FETCHING; this.eventEmitter = new EventEmitter(config, participant, this.store); } AllocationStatus getAllocationStatus() { return allocationStatus; } void sandBagConfirmation() { confirmationSandbagged = true; } void sandBagContamination() { contaminationSandbagged = true; } String createAllocationsUrl() { try { String path = String.format("//%s/%s/%s/allocations", config.getDomain(), config.getVersion(), config.getEnvironmentId()); String queryString = String.format("uid=%s&sid=%s", participant.getUserId(), participant.getSessionId()); URI uri = new URI(config.getHttpScheme(), null, path, queryString, null); URL url = uri.toURL(); return url.toString(); } catch (Exception e) { LOGGER.error("There was an issue creating the allocations url.", e); return ""; } } CompletableFuture<JsonArray> fetchAllocations() { CompletableFuture<String> responseFuture = httpClient.get(createAllocationsUrl()); return responseFuture.thenApply(responseBody -> { JsonParser parser = new JsonParser(); JsonArray allocations = parser.parse(responseBody).getAsJsonArray(); JsonArray previousAllocations = store.get(participant.getUserId()); if (allocationsNotEmpty(previousAllocations)) { allocations = Allocations.reconcileAllocations(previousAllocations, allocations); } store.put(participant.getUserId(), allocations); allocationStatus = AllocationStatus.RETRIEVED; executionQueue.executeAllWithValuesFromAllocations(allocations, eventEmitter, confirmationSandbagged, contaminationSandbagged); return allocations; }).exceptionally(e -> { LOGGER.error("There was an exception while retrieving allocations.", e); return resolveAllocationFailure(); }); } JsonArray resolveAllocationFailure() { JsonArray previousAllocations = store.get(participant.getUserId()); if (allocationsNotEmpty(previousAllocations)) { LOGGER.debug("Falling back to participant's previous allocation."); allocationStatus = AllocationStatus.RETRIEVED; executionQueue.executeAllWithValuesFromAllocations(previousAllocations, eventEmitter, confirmationSandbagged, contaminationSandbagged); } else { LOGGER.debug("Falling back to the supplied defaults."); allocationStatus = AllocationStatus.FAILED; executionQueue.executeAllWithValuesFromDefaults(); previousAllocations = new JsonArray(); } return previousAllocations; } static boolean allocationsNotEmpty(JsonArray allocations) { return allocations != null && allocations.size() > 0; } }
0
java-sources/ai/evolv/ascend-sdk/0.7.1/ai
java-sources/ai/evolv/ascend-sdk/0.7.1/ai/evolv/AscendClientFactory.java
package ai.evolv; import com.google.gson.JsonArray; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AscendClientFactory { private static final Logger LOGGER = LoggerFactory.getLogger(AscendClientFactory.class); /** * Creates instances of the AscendClient. * * @param config an instance of AscendConfig * @return an instance of AscendClient */ public static AscendClient init(AscendConfig config) { LOGGER.debug("Initializing Ascend Client."); AscendParticipant participant = config.getAscendParticipant(); if (participant == null) { participant = AscendParticipant.builder().build(); } return AscendClientFactory.createClient(config, participant); } /** * Creates instances of the AscendClient. * * @param config general configurations for the SDK * @param participant the participant for the initialized client * @return an instance of AscendClient */ public static AscendClient init(AscendConfig config, AscendParticipant participant) { LOGGER.debug("Initializing Ascend Client."); return AscendClientFactory.createClient(config, participant); } private static AscendClient createClient(AscendConfig config, AscendParticipant participant) { AscendAllocationStore store = config.getAscendAllocationStore(); JsonArray previousAllocations = store.get(participant.getUserId()); boolean reconciliationNeeded = false; if (Allocator.allocationsNotEmpty(previousAllocations)) { reconciliationNeeded = true; } Allocator allocator = new Allocator(config, participant); // fetch and reconcile allocations asynchronously CompletableFuture<JsonArray> futureAllocations = allocator.fetchAllocations(); return new AscendClientImpl(config, new EventEmitter(config, participant, store), futureAllocations, allocator, reconciliationNeeded, participant); } }