<commit_before>/*
 * Copyright 2013 Jive Software, Inc
 *
 * 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 com.jivesoftware.os.upena.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.jivesoftware.os.amza.api.partition.Consistency;
import com.jivesoftware.os.amza.api.partition.Durability;
import com.jivesoftware.os.amza.api.partition.PartitionName;
import com.jivesoftware.os.amza.api.partition.PartitionProperties;
import com.jivesoftware.os.amza.api.stream.RowType;
import com.jivesoftware.os.amza.service.AmzaService;
import com.jivesoftware.os.amza.service.EmbeddedClientProvider;
import com.jivesoftware.os.amza.service.EmbeddedClientProvider.CheckOnline;
import com.jivesoftware.os.amza.service.EmbeddedClientProvider.EmbeddedClient;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import com.jivesoftware.os.upena.amza.service.AmzaTable;
import com.jivesoftware.os.upena.amza.service.UpenaAmzaService;
import com.jivesoftware.os.upena.amza.shared.TableName;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class UpenaConfigStore {

    public static final MetricLogger LOG = MetricLoggerFactory.getLogger();

    private final ObjectMapper mapper;
    private final UpenaAmzaService upenaAmzaService;
    private final AmzaService amzaService;
    private final EmbeddedClientProvider embeddedClientProvider;
    private final Map<String, FetchedVersion> lastFetchedVersion = Maps.newConcurrentMap();

    private final PartitionProperties partitionProperties = new PartitionProperties(Durability.fsync_async,
        TimeUnit.DAYS.toMillis(30), TimeUnit.DAYS.toMillis(10), TimeUnit.DAYS.toMillis(30), TimeUnit.DAYS.toMillis(10),
        0, 0, 0, 0,
        false, Consistency.quorum, true, true, false, RowType.snappy_primary, "lab", -1, null, -1, -1);

    public UpenaConfigStore(ObjectMapper mapper,
        UpenaAmzaService upenaAmzaService,
        AmzaService amzaService,
        EmbeddedClientProvider embeddedClientProvider) throws Exception {

        this.mapper = mapper;
        this.upenaAmzaService = upenaAmzaService;
        this.amzaService = amzaService;
        this.embeddedClientProvider = embeddedClientProvider;
    }


    public void init() throws Exception {

        if (upenaAmzaService != null) {
            EmbeddedClient client = client();
            TableName tableName = new TableName("master", "config", null, null);
            AmzaTable table = upenaAmzaService.getTable(tableName);
            long[] count = { 0 };
            table.scan((transactionId, key, value) -> {
                count[0]++;
                client.commit(Consistency.quorum, null,
                    commitKeyValueStream -> commitKeyValueStream.commit(key.getKey(), value.getValue(), value.getTimestampId(), value.getTombstoned()),
                    30_000, TimeUnit.MILLISECONDS);
                return true;
            });
            LOG.info("UPGRADE: carried {} configs forward.", count[0]);
        }
    }

    private EmbeddedClient client() throws Exception {
        PartitionName partitionName = new PartitionName(false, "upena".getBytes(), ("upena-config").getBytes());
        while (true) {
            try {
                amzaService.getRingWriter().ensureMaximalRing(partitionName.getRingName(), 30_000L); //TODO config
                amzaService.createPartitionIfAbsent(partitionName, partitionProperties);
                amzaService.awaitOnline(partitionName, 30_000L); //TODO config
                return embeddedClientProvider.getClient(partitionName, CheckOnline.once);
            } catch (Exception x) {
                LOG.warn("Failed to get client for " + partitionName.getName() + ". Retrying...", x);
            }
        }
    }


    private String createTableName(String instanceKey, String context) {
        return "config/" + instanceKey + "/" + context;
    }


    synchronized private byte[] get(String instanceKey, String context) throws Exception {
        String key = createTableName(instanceKey, context);
        return client().getValue(Consistency.none, null, key.getBytes(StandardCharsets.UTF_8));
    }

    synchronized private void set(String instanceKey, String context, byte[] rawProperties) throws Exception {
        String key = createTableName(instanceKey, context);
        client().commit(Consistency.quorum, null,
            commitKeyValueStream -> commitKeyValueStream.commit(key.getBytes(StandardCharsets.UTF_8), rawProperties, -1L, false),
            30_000, TimeUnit.MILLISECONDS);
    }


    synchronized public void remove(String instanceKey, String context) throws Exception {
        String key = createTableName(instanceKey, context);
        client().commit(Consistency.quorum, null,
            commitKeyValueStream -> commitKeyValueStream.commit(key.getBytes(StandardCharsets.UTF_8), null, -1L, true),<commit_msg>Had to move UpenaConfigStore off current time and onto orderid to be compatable with legacy state<commit_after>/*
 * Copyright 2013 <NAME>, Inc
 *
 * 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 com.jivesoftware.os.upena.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.jivesoftware.os.amza.api.partition.Consistency;
import com.jivesoftware.os.amza.api.partition.Durability;
import com.jivesoftware.os.amza.api.partition.PartitionName;
import com.jivesoftware.os.amza.api.partition.PartitionProperties;
import com.jivesoftware.os.amza.api.stream.RowType;
import com.jivesoftware.os.amza.service.AmzaService;
import com.jivesoftware.os.amza.service.EmbeddedClientProvider;
import com.jivesoftware.os.amza.service.EmbeddedClientProvider.CheckOnline;
import com.jivesoftware.os.amza.service.EmbeddedClientProvider.EmbeddedClient;
import com.jivesoftware.os.jive.utils.ordered.id.TimestampedOrderIdProvider;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import com.jivesoftware.os.upena.amza.service.AmzaTable;
import com.jivesoftware.os.upena.amza.service.UpenaAmzaService;
import com.jivesoftware.os.upena.amza.shared.TableName;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class UpenaConfigStore {

    public static final MetricLogger LOG = MetricLoggerFactory.getLogger();

    private final TimestampedOrderIdProvider orderIdProvider;
    private final ObjectMapper mapper;
    private final UpenaAmzaService upenaAmzaService;
    private final AmzaService amzaService;
    private final EmbeddedClientProvider embeddedClientProvider;
    private final Map<String, FetchedVersion> lastFetchedVersion = Maps.newConcurrentMap();

    private final PartitionProperties partitionProperties = new PartitionProperties(Durability.fsync_async,
        TimeUnit.DAYS.toMillis(30), TimeUnit.DAYS.toMillis(10), TimeUnit.DAYS.toMillis(30), TimeUnit.DAYS.toMillis(10),
        0, 0, 0, 0,
        false, Consistency.quorum, true, true, false, RowType.snappy_primary, "lab", -1, null, -1, -1);

    public UpenaConfigStore(TimestampedOrderIdProvider orderIdProvider,
        ObjectMapper mapper,
        UpenaAmzaService upenaAmzaService,
        AmzaService amzaService,
        EmbeddedClientProvider embeddedClientProvider) throws Exception {

        this.orderIdProvider = orderIdProvider;
        this.mapper = mapper;
        this.upenaAmzaService = upenaAmzaService;
        this.amzaService = amzaService;
        this.embeddedClientProvider = embeddedClientProvider;
    }


    public void init() throws Exception {

        if (upenaAmzaService != null) {
            EmbeddedClient client = client();
            TableName tableName = new TableName("master", "config", null, null);
            AmzaTable table = upenaAmzaService.getTable(tableName);
            long[] count = { 0 };
            table.scan((transactionId, key, value) -> {
                count[0]++;
                client.commit(Consistency.quorum, null,
                    commitKeyValueStream -> commitKeyValueStream.commit(key.getKey(), value.getValue(), value.getTimestampId(), value.getTombstoned()),
                    30_000, TimeUnit.MILLISECONDS);
                return true;
            });
            LOG.info("UPGRADE: carried {} configs forward.", count[0]);
        }
    }

    private EmbeddedClient client() throws Exception {
        PartitionName partitionName = new PartitionName(false, "upena".getBytes(), ("upena-config").getBytes());
        while (true) {
            try {
                amzaService.getRingWriter().ensureMaximalRing(partitionName.getRingName(), 30_000L); //TODO config
                amzaService.createPartitionIfAbsent(partitionName, partitionProperties);
                amzaService.awaitOnline(partitionName, 30_000L); //TODO config
                return embeddedClientProvider.getClient(partitionName, CheckOnline.once);
            } catch (Exception x) {
                LOG.warn("Failed to get client for " + partitionName.getName() + ". Retrying...", x);
            }
        }
    }


    private String createTableName(String instanceKey, String context) {
        return "config/" + instanceKey + "/" + context;
    }


    synchronized private byte[] get(String instanceKey, String context) throws Exception {
        String key = createTableName(instanceKey, context);
        return client().getValue(Consistency.none, null, key.getBytes(StandardCharsets.UTF_8));
    }

    synchronized private void set(String instanceKey, String context, byte[] rawProperties) throws Exception {
        String key = createTableName(instanceKey, context);
        client().commit(Consistency.quorum, null,
            commitKeyValueStream -> commitKeyValueStream.commit(key.getBytes(StandardCharsets.UTF_8), rawProperties, orderIdProvider.nextId(), false),
            30_000, TimeUnit.MILLISECONDS);
    }


    synchronized public void remove(String instanceKey, String context) throws Exception {
        String key = createTableName(instanceKey, context);
        client().commit(Consistency.quorum, null,
            commitKeyValueStream -> commitKeyValueStream.commit(key.getBytes(StandardCharsets.UTF_8), null, orderIdProvider.nextId(), true),
{'fraction_non_alphanumeric': 0.096160409556314, 'fraction_numerical': 0.008532423208191127, 'mean_word_length': 3.610936270653029, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7593733', 'n_tokens_mistral': 3393, 'n_tokens_neox': 3265, 'n_words': 747}