shibd commented on code in PR #18489:
URL: https://github.com/apache/pulsar/pull/18489#discussion_r1029961985


##########
pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelTest.java:
##########
@@ -0,0 +1,796 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.apache.pulsar.broker.loadbalance.extensions.channel;
+
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MAX_CLEAN_UP_DELAY_TIME_IN_SECS;
+import static 
org.apache.pulsar.metadata.api.extended.SessionEvent.ConnectionLost;
+import static org.apache.pulsar.metadata.api.extended.SessionEvent.Reconnected;
+import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionLost;
+import static 
org.apache.pulsar.metadata.api.extended.SessionEvent.SessionReestablished;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
+import static org.hamcrest.Matchers.lessThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import static org.testng.AssertJUnit.assertNotNull;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest;
+import org.apache.pulsar.broker.loadbalance.LeaderElectionService;
+import org.apache.pulsar.broker.loadbalance.extensions.models.Split;
+import org.apache.pulsar.broker.loadbalance.extensions.models.Unload;
+import org.apache.pulsar.client.api.Producer;
+import org.apache.pulsar.client.api.TypedMessageBuilder;
+import org.apache.pulsar.client.impl.TableViewImpl;
+import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.extended.SessionEvent;
+import org.awaitility.Awaitility;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class ServiceUnitStateChannelTest extends MockedPulsarServiceBaseTest {
+
+    private PulsarService pulsar1;
+    private PulsarService pulsar2;
+    private ServiceUnitStateChannel channel1;
+    private ServiceUnitStateChannel channel2;
+    private String lookupServiceAddress1;
+    private String lookupServiceAddress2;
+    private String bundle;
+
+    private String bundle1;
+    private String bundle2;
+
+    @BeforeClass
+    @Override
+    protected void setup() throws Exception {
+        conf.setAllowAutoTopicCreation(true);
+        super.internalSetup(conf);
+
+        admin.tenants().createTenant("pulsar", createDefaultTenantInfo());
+        admin.namespaces().createNamespace("pulsar/system");
+        admin.tenants().createTenant("public", createDefaultTenantInfo());
+        admin.namespaces().createNamespace("public/default");
+
+        pulsar1 = pulsar;
+        pulsar2 = startBrokerWithoutAuthorization(getDefaultConf());
+        channel1 = new ServiceUnitStateChannelImpl(pulsar1);
+        channel1.start();
+        channel2 = new ServiceUnitStateChannelImpl(pulsar2);
+        channel2.start();
+        lookupServiceAddress1 = (String)
+                FieldUtils.readDeclaredField(channel1, "lookupServiceAddress", 
true);
+        lookupServiceAddress2 = (String)
+                FieldUtils.readDeclaredField(channel2, "lookupServiceAddress", 
true);
+
+        bundle = String.format("%s/%s", "public/default", 
"0x00000000_0xffffffff");
+        bundle1 = String.format("%s/%s", "public/default", 
"0x00000000_0xfffffff0");
+        bundle2 = String.format("%s/%s", "public/default", 
"0xfffffff0_0xffffffff");
+    }
+
+    @BeforeMethod
+    protected void initTableViews() throws Exception {
+        cleanTableView(channel1, bundle);
+        cleanTableView(channel2, bundle);
+    }
+
+
+    @AfterClass
+    @Override
+    protected void cleanup() throws Exception {
+        channel1.close();
+        channel2.close();
+        pulsar1 = null;
+        pulsar2.close();
+        super.internalCleanup();
+    }
+
+    @Test(priority = 0)
+    public void channelOwnerTest() throws Exception {
+        var channelOwner1 = channel1.getChannelOwner();
+        var channelOwner2 = channel2.getChannelOwner();
+        assertEquals(channelOwner1, channelOwner2);
+        LeaderElectionService leaderElectionService1 = (LeaderElectionService) 
FieldUtils.readDeclaredField(
+                channel1, "leaderElectionService", true);
+        leaderElectionService1.close();
+        waitUntilNewChannelOwner(channel2, channelOwner1);
+        leaderElectionService1.start();
+        waitUntilNewChannelOwner(channel1, channelOwner1);
+
+        var newChannelOwner1 = channel1.getChannelOwner();
+        var newChannelOwner2 = channel2.getChannelOwner();
+
+        assertEquals(newChannelOwner1, newChannelOwner2);
+        assertNotEquals(channelOwner1, newChannelOwner1);
+
+        if (newChannelOwner1.equals(lookupServiceAddress1)) {
+            assertTrue(channel1.isChannelOwner());
+            assertFalse(channel2.isChannelOwner());
+        } else {
+            assertFalse(channel1.isChannelOwner());
+            assertTrue(channel2.isChannelOwner());
+        }
+    }
+
+    @Test(priority = 0)
+    public void channelValidationTest()
+            throws ExecutionException, InterruptedException, 
IllegalAccessException, PulsarServerException {
+        var channel = new ServiceUnitStateChannelImpl(pulsar);
+        int errorCnt = validateChannelStart(channel);
+        assertEquals(6, errorCnt);
+        ExecutorService executor = Executors.newSingleThreadExecutor();
+        Future startFuture = executor.submit(() -> {
+            try {
+                channel.start();
+            } catch (PulsarServerException e) {
+                throw new RuntimeException(e);
+            }
+        });
+        errorCnt = validateChannelStart(channel);
+        startFuture.get();
+        assertTrue(errorCnt > 0);
+
+        FieldUtils.writeDeclaredField(channel, "channelState",
+                
ServiceUnitStateChannelImpl.ChannelState.LeaderElectionServiceStarted, true);
+        assertNotNull(channel.getChannelOwner());
+
+        Future closeFuture = executor.submit(()->{
+            try {
+                channel.close();
+            } catch (PulsarServerException e) {
+                throw new RuntimeException(e);
+            }
+        });
+        errorCnt = validateChannelStart(channel);
+        closeFuture.get();
+        assertTrue(errorCnt > 0);
+        errorCnt = validateChannelStart(channel);
+        assertEquals(6, errorCnt);
+
+        // check if we can close() again
+        channel.close();
+        errorCnt = validateChannelStart(channel);
+        assertEquals(6, errorCnt);
+
+        // close() -> start() test.
+        channel.start();
+        assertNotNull(channel.getChannelOwner());
+
+        // start() -> start() test.
+        IllegalStateException ex = null;

Review Comment:
   Suggestion use:  `assertThrows(IllegalStateException.class, () -> 
channel.start());`



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelImpl.java:
##########
@@ -0,0 +1,778 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.apache.pulsar.broker.loadbalance.extensions.channel;
+
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Assigned;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Free;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Owned;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Released;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Splitting;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.Closed;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.Constructed;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.LeaderElectionServiceStarted;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.Started;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Jittery;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Stable;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Unstable;
+import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionLost;
+import static 
org.apache.pulsar.metadata.api.extended.SessionEvent.SessionReestablished;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.mutable.MutableInt;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.loadbalance.LeaderBroker;
+import org.apache.pulsar.broker.loadbalance.LeaderElectionService;
+import org.apache.pulsar.broker.loadbalance.extensions.models.Split;
+import org.apache.pulsar.broker.loadbalance.extensions.models.Unload;
+import org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared;
+import org.apache.pulsar.client.admin.PulsarAdminException;
+import org.apache.pulsar.client.api.MessageId;
+import org.apache.pulsar.client.api.Producer;
+import org.apache.pulsar.client.api.Schema;
+import org.apache.pulsar.client.api.TableView;
+import org.apache.pulsar.common.naming.NamespaceBundle;
+import org.apache.pulsar.common.naming.NamespaceBundleSplitAlgorithm;
+import org.apache.pulsar.common.naming.NamespaceName;
+import org.apache.pulsar.common.naming.TopicDomain;
+import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.coordination.LeaderElectionState;
+import org.apache.pulsar.metadata.api.extended.SessionEvent;
+
+@Slf4j
+public class ServiceUnitStateChannelImpl implements ServiceUnitStateChannel {
+    public static final String TOPIC =
+            TopicDomain.persistent.value()
+                    + "://"
+                    + NamespaceName.SYSTEM_NAMESPACE
+                    + "/service-unit-state-channel";
+    // TODO: define StateCompactionStrategy
+    private static final long COMPACTION_THRESHOLD = 5 * 1024 * 1024; // 5mb
+    private static final long MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS = 30 
* 1000; // 30sec
+    public static final long MAX_CLEAN_UP_DELAY_TIME_IN_SECS = 3 * 60; // 3 
mins
+    private static final long MIN_CLEAN_UP_DELAY_TIME_IN_SECS = 0; // 0 secs 
to clean immediately
+    private static final int MAX_OUTSTANDING_PUB_MESSAGES = 500;
+    private final PulsarService pulsar;
+    private final Schema<ServiceUnitStateData> schema;
+    private final ConcurrentOpenHashMap<String, CompletableFuture<String>> 
getOwnerRequests;
+    private final String lookupServiceAddress;
+    // TODO: define BrokerRegistry
+    private final Semaphore outstandingCleanupTombstoneMessages;
+    private final ConcurrentOpenHashMap<String, CompletableFuture<Void>> 
cleanupJobs;
+    private final LeaderElectionService leaderElectionService;
+    private TableView<ServiceUnitStateData> tableview;
+    private Producer<ServiceUnitStateData> producer;
+    private ScheduledFuture<?> cleanupTasks;
+    private SessionEvent lastMetadataSessionEvent = SessionReestablished;
+    private long lastMetadataSessionEventTimestamp = 0;
+    private long inFlightStateWaitingTimeInMillis;
+    private long maxCleanupDelayTimeInSecs;
+    private long minCleanupDelayTimeInSecs;
+    // cleanup metrics
+    private long totalCleanupCnt = 0;
+    private long totalBrokerCleanupTombstoneCnt = 0;
+    private long totalServiceUnitCleanupTombstoneCnt = 0;
+    private long totalServiceUnitCleanupErrorCnt = 0;
+    private long totalCleanupScheduledCnt = 0;
+    private long totalCleanupIgnoredCnt = 0;
+    private long totalCleanupCancelledCnt = 0;
+    private volatile ChannelState channelState;
+
+    enum ChannelState {
+        Closed(0),
+        Constructed(1),
+        LeaderElectionServiceStarted(2),
+        Started(3);
+
+        ChannelState(int id) {
+            this.id = id;
+        }
+        int id;
+    }
+
+    enum MetadataState {
+        Stable,
+        Jittery,
+        Unstable
+    }
+
+    public ServiceUnitStateChannelImpl(PulsarService pulsar) {
+        this.pulsar = pulsar;
+        this.lookupServiceAddress = pulsar.getLookupServiceAddress();
+        this.schema = Schema.JSON(ServiceUnitStateData.class);
+        this.outstandingCleanupTombstoneMessages = new 
Semaphore(MAX_OUTSTANDING_PUB_MESSAGES);
+        this.getOwnerRequests = ConcurrentOpenHashMap.<String,
+                CompletableFuture<String>>newBuilder().build();
+        this.cleanupJobs = ConcurrentOpenHashMap.<String, 
CompletableFuture<Void>>newBuilder().build();
+        this.inFlightStateWaitingTimeInMillis = 
MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS;
+        this.maxCleanupDelayTimeInSecs = MAX_CLEAN_UP_DELAY_TIME_IN_SECS;
+        this.minCleanupDelayTimeInSecs = MIN_CLEAN_UP_DELAY_TIME_IN_SECS;
+        this.leaderElectionService = new LeaderElectionService(
+                pulsar.getCoordinationService(), 
pulsar.getSafeWebServiceAddress(),
+                state -> {
+                    if (state == LeaderElectionState.Leading) {
+                        log.debug("This broker:{} is the leader now.", 
lookupServiceAddress);
+                        // TODO: schedule monitorOwnerships by brokerRegistry
+                    } else {
+                        log.debug("This broker:{} is a follower now.", 
lookupServiceAddress);
+                        // TODO: cancel scheduled monitorOwnerships if any
+                    }
+                });
+        this.channelState = Constructed;
+    }
+
+    public synchronized void start() throws PulsarServerException {
+        validateChannelState(LeaderElectionServiceStarted, false);
+        try {
+            leaderElectionService.start();
+            this.channelState = LeaderElectionServiceStarted;
+            log.debug("Successfully started the channel leader election 
service.");
+
+            if (producer != null) {
+                producer.close();
+                log.debug("Closed the channel producer.");
+            }
+            producer = pulsar.getClient().newProducer(schema)
+                    .enableBatching(true)
+                    .topic(TOPIC)
+                    .create();
+
+            log.debug("Successfully started the channel producer.");
+
+            if (tableview != null) {
+                tableview.close();
+                log.debug("Closed the channel tableview.");
+            }
+            tableview = pulsar.getClient().newTableViewBuilder(schema)
+                    .topic(TOPIC)
+                    // TODO: enable CompactionStrategy
+                    .create();
+            // TODO: schedule listen instead of foreachAndListen
+            tableview.forEachAndListen((key, value) -> handle(key, value));
+            log.debug("Successfully started the channel tableview.");
+
+            
pulsar.getLocalMetadataStore().registerSessionListener(this::handleMetadataSessionEvent);
+            log.debug("Successfully registered the 
handleMetadataSessionEvent");
+
+            channelState = Started;
+            log.info("Successfully started the channel.");
+        } catch (Exception e) {
+            String msg = "Failed to start the channel.";
+            log.error(msg, e);
+            throw new PulsarServerException(msg, e);
+        }
+    }
+
+    public synchronized void close() throws PulsarServerException {
+        channelState = Closed;
+        try {
+            leaderElectionService.close();
+            log.debug("Successfully closed the channel leader election 
service.");
+
+            if (tableview != null) {
+                tableview.close();
+                tableview = null;
+                log.debug("Successfully closed the channel tableview.");
+            }
+
+            if (producer != null) {
+                producer.close();
+                producer = null;
+                log.info("Successfully closed the channel producer.");
+            }
+
+            // TODO: clean brokerRegistry
+
+            if (cleanupTasks != null) {
+                cleanupTasks.cancel(true);
+                cleanupTasks = null;
+                log.info("Successfully cancelled the cleanup tasks");
+            }
+
+            log.info("Successfully closed the channel.");
+
+        } catch (Exception e) {
+            String msg = "Failed to close the channel.";
+            log.error(msg, e);
+            throw new PulsarServerException(msg, e);
+        }
+    }
+
+    private void validateChannelState(ChannelState targetState, boolean 
checkLowerIds) {
+        int order = checkLowerIds ? -1 : 1;
+        if (Integer.compare(channelState.id, targetState.id) * order > 0) {
+            throw new IllegalStateException("Invalid channel state:" + 
channelState.name());
+        }
+    }
+
+    public synchronized void scheduleCompaction() throws PulsarServerException 
{
+        try {
+            Long threshold = pulsar.getAdminClient().topicPolicies()
+                    .getCompactionThreshold(TOPIC);
+            if (threshold == null || threshold == 0) {
+                pulsar.getAdminClient().topicPolicies()
+                        .setCompactionThreshold(TOPIC, COMPACTION_THRESHOLD);
+                log.info("Scheduled compaction on topic:{}, threshold:{} 
bytes", TOPIC, COMPACTION_THRESHOLD);
+            } else {
+                log.info("Already set compaction on topic:{}, threshold:{} 
bytes", TOPIC, COMPACTION_THRESHOLD);
+            }
+        } catch (PulsarAdminException e) {
+            throw new PulsarServerException("Failed to schedule compaction.", 
e);
+        }
+    }
+
+    public String getChannelOwner() {
+        validateChannelState(LeaderElectionServiceStarted, true);
+        CompletableFuture<Optional<LeaderBroker>> future = 
leaderElectionService.readCurrentLeader();
+        if (!future.isDone()) {

Review Comment:
   When the future is not done, we should wait for it, right? We should remove 
255~257, otherwise unit test `channelValidationTest` doesn't pass.



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelImpl.java:
##########
@@ -0,0 +1,778 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.apache.pulsar.broker.loadbalance.extensions.channel;
+
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Assigned;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Free;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Owned;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Released;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Splitting;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.Closed;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.Constructed;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.LeaderElectionServiceStarted;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.Started;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Jittery;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Stable;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Unstable;
+import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionLost;
+import static 
org.apache.pulsar.metadata.api.extended.SessionEvent.SessionReestablished;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.mutable.MutableInt;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.loadbalance.LeaderBroker;
+import org.apache.pulsar.broker.loadbalance.LeaderElectionService;
+import org.apache.pulsar.broker.loadbalance.extensions.models.Split;
+import org.apache.pulsar.broker.loadbalance.extensions.models.Unload;
+import org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared;
+import org.apache.pulsar.client.admin.PulsarAdminException;
+import org.apache.pulsar.client.api.MessageId;
+import org.apache.pulsar.client.api.Producer;
+import org.apache.pulsar.client.api.Schema;
+import org.apache.pulsar.client.api.TableView;
+import org.apache.pulsar.common.naming.NamespaceBundle;
+import org.apache.pulsar.common.naming.NamespaceBundleSplitAlgorithm;
+import org.apache.pulsar.common.naming.NamespaceName;
+import org.apache.pulsar.common.naming.TopicDomain;
+import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.coordination.LeaderElectionState;
+import org.apache.pulsar.metadata.api.extended.SessionEvent;
+
+@Slf4j
+public class ServiceUnitStateChannelImpl implements ServiceUnitStateChannel {
+    public static final String TOPIC =
+            TopicDomain.persistent.value()
+                    + "://"
+                    + NamespaceName.SYSTEM_NAMESPACE
+                    + "/service-unit-state-channel";
+    // TODO: define StateCompactionStrategy
+    private static final long COMPACTION_THRESHOLD = 5 * 1024 * 1024; // 5mb
+    private static final long MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS = 30 
* 1000; // 30sec
+    public static final long MAX_CLEAN_UP_DELAY_TIME_IN_SECS = 3 * 60; // 3 
mins
+    private static final long MIN_CLEAN_UP_DELAY_TIME_IN_SECS = 0; // 0 secs 
to clean immediately
+    private static final int MAX_OUTSTANDING_PUB_MESSAGES = 500;
+    private final PulsarService pulsar;
+    private final Schema<ServiceUnitStateData> schema;
+    private final ConcurrentOpenHashMap<String, CompletableFuture<String>> 
getOwnerRequests;
+    private final String lookupServiceAddress;
+    // TODO: define BrokerRegistry
+    private final Semaphore outstandingCleanupTombstoneMessages;
+    private final ConcurrentOpenHashMap<String, CompletableFuture<Void>> 
cleanupJobs;
+    private final LeaderElectionService leaderElectionService;
+    private TableView<ServiceUnitStateData> tableview;
+    private Producer<ServiceUnitStateData> producer;
+    private ScheduledFuture<?> cleanupTasks;
+    private SessionEvent lastMetadataSessionEvent = SessionReestablished;
+    private long lastMetadataSessionEventTimestamp = 0;
+    private long inFlightStateWaitingTimeInMillis;
+    private long maxCleanupDelayTimeInSecs;
+    private long minCleanupDelayTimeInSecs;
+    // cleanup metrics
+    private long totalCleanupCnt = 0;
+    private long totalBrokerCleanupTombstoneCnt = 0;
+    private long totalServiceUnitCleanupTombstoneCnt = 0;
+    private long totalServiceUnitCleanupErrorCnt = 0;
+    private long totalCleanupScheduledCnt = 0;
+    private long totalCleanupIgnoredCnt = 0;
+    private long totalCleanupCancelledCnt = 0;
+    private volatile ChannelState channelState;
+
+    enum ChannelState {
+        Closed(0),
+        Constructed(1),
+        LeaderElectionServiceStarted(2),
+        Started(3);
+
+        ChannelState(int id) {
+            this.id = id;
+        }
+        int id;
+    }
+
+    enum MetadataState {
+        Stable,
+        Jittery,
+        Unstable
+    }
+
+    public ServiceUnitStateChannelImpl(PulsarService pulsar) {
+        this.pulsar = pulsar;
+        this.lookupServiceAddress = pulsar.getLookupServiceAddress();
+        this.schema = Schema.JSON(ServiceUnitStateData.class);
+        this.outstandingCleanupTombstoneMessages = new 
Semaphore(MAX_OUTSTANDING_PUB_MESSAGES);
+        this.getOwnerRequests = ConcurrentOpenHashMap.<String,
+                CompletableFuture<String>>newBuilder().build();
+        this.cleanupJobs = ConcurrentOpenHashMap.<String, 
CompletableFuture<Void>>newBuilder().build();
+        this.inFlightStateWaitingTimeInMillis = 
MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS;
+        this.maxCleanupDelayTimeInSecs = MAX_CLEAN_UP_DELAY_TIME_IN_SECS;
+        this.minCleanupDelayTimeInSecs = MIN_CLEAN_UP_DELAY_TIME_IN_SECS;
+        this.leaderElectionService = new LeaderElectionService(
+                pulsar.getCoordinationService(), 
pulsar.getSafeWebServiceAddress(),
+                state -> {
+                    if (state == LeaderElectionState.Leading) {
+                        log.debug("This broker:{} is the leader now.", 
lookupServiceAddress);
+                        // TODO: schedule monitorOwnerships by brokerRegistry
+                    } else {
+                        log.debug("This broker:{} is a follower now.", 
lookupServiceAddress);
+                        // TODO: cancel scheduled monitorOwnerships if any
+                    }
+                });
+        this.channelState = Constructed;
+    }
+
+    public synchronized void start() throws PulsarServerException {
+        validateChannelState(LeaderElectionServiceStarted, false);
+        try {
+            leaderElectionService.start();
+            this.channelState = LeaderElectionServiceStarted;
+            log.debug("Successfully started the channel leader election 
service.");
+
+            if (producer != null) {
+                producer.close();
+                log.debug("Closed the channel producer.");
+            }
+            producer = pulsar.getClient().newProducer(schema)
+                    .enableBatching(true)
+                    .topic(TOPIC)
+                    .create();
+
+            log.debug("Successfully started the channel producer.");
+
+            if (tableview != null) {
+                tableview.close();
+                log.debug("Closed the channel tableview.");
+            }
+            tableview = pulsar.getClient().newTableViewBuilder(schema)
+                    .topic(TOPIC)
+                    // TODO: enable CompactionStrategy
+                    .create();
+            // TODO: schedule listen instead of foreachAndListen
+            tableview.forEachAndListen((key, value) -> handle(key, value));
+            log.debug("Successfully started the channel tableview.");
+
+            
pulsar.getLocalMetadataStore().registerSessionListener(this::handleMetadataSessionEvent);
+            log.debug("Successfully registered the 
handleMetadataSessionEvent");
+
+            channelState = Started;
+            log.info("Successfully started the channel.");
+        } catch (Exception e) {
+            String msg = "Failed to start the channel.";
+            log.error(msg, e);
+            throw new PulsarServerException(msg, e);
+        }
+    }
+
+    public synchronized void close() throws PulsarServerException {
+        channelState = Closed;
+        try {
+            leaderElectionService.close();
+            log.debug("Successfully closed the channel leader election 
service.");
+
+            if (tableview != null) {
+                tableview.close();
+                tableview = null;
+                log.debug("Successfully closed the channel tableview.");
+            }
+
+            if (producer != null) {
+                producer.close();
+                producer = null;
+                log.info("Successfully closed the channel producer.");
+            }
+
+            // TODO: clean brokerRegistry
+
+            if (cleanupTasks != null) {
+                cleanupTasks.cancel(true);
+                cleanupTasks = null;
+                log.info("Successfully cancelled the cleanup tasks");
+            }
+
+            log.info("Successfully closed the channel.");
+
+        } catch (Exception e) {
+            String msg = "Failed to close the channel.";
+            log.error(msg, e);
+            throw new PulsarServerException(msg, e);
+        }
+    }
+
+    private void validateChannelState(ChannelState targetState, boolean 
checkLowerIds) {
+        int order = checkLowerIds ? -1 : 1;
+        if (Integer.compare(channelState.id, targetState.id) * order > 0) {
+            throw new IllegalStateException("Invalid channel state:" + 
channelState.name());
+        }
+    }
+
+    public synchronized void scheduleCompaction() throws PulsarServerException 
{

Review Comment:
   Who called this method? It looks like we only need to call it once at the 
start.



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelImpl.java:
##########
@@ -0,0 +1,778 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.apache.pulsar.broker.loadbalance.extensions.channel;
+
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Assigned;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Free;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Owned;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Released;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Splitting;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.Closed;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.Constructed;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.LeaderElectionServiceStarted;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.ChannelState.Started;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Jittery;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Stable;
+import static 
org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Unstable;
+import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionLost;
+import static 
org.apache.pulsar.metadata.api.extended.SessionEvent.SessionReestablished;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.mutable.MutableInt;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.loadbalance.LeaderBroker;
+import org.apache.pulsar.broker.loadbalance.LeaderElectionService;
+import org.apache.pulsar.broker.loadbalance.extensions.models.Split;
+import org.apache.pulsar.broker.loadbalance.extensions.models.Unload;
+import org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared;
+import org.apache.pulsar.client.admin.PulsarAdminException;
+import org.apache.pulsar.client.api.MessageId;
+import org.apache.pulsar.client.api.Producer;
+import org.apache.pulsar.client.api.Schema;
+import org.apache.pulsar.client.api.TableView;
+import org.apache.pulsar.common.naming.NamespaceBundle;
+import org.apache.pulsar.common.naming.NamespaceBundleSplitAlgorithm;
+import org.apache.pulsar.common.naming.NamespaceName;
+import org.apache.pulsar.common.naming.TopicDomain;
+import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.coordination.LeaderElectionState;
+import org.apache.pulsar.metadata.api.extended.SessionEvent;
+
+@Slf4j
+public class ServiceUnitStateChannelImpl implements ServiceUnitStateChannel {
+    public static final String TOPIC =
+            TopicDomain.persistent.value()
+                    + "://"
+                    + NamespaceName.SYSTEM_NAMESPACE
+                    + "/service-unit-state-channel";
+    // TODO: define StateCompactionStrategy
+    private static final long COMPACTION_THRESHOLD = 5 * 1024 * 1024; // 5mb
+    private static final long MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS = 30 
* 1000; // 30sec
+    public static final long MAX_CLEAN_UP_DELAY_TIME_IN_SECS = 3 * 60; // 3 
mins
+    private static final long MIN_CLEAN_UP_DELAY_TIME_IN_SECS = 0; // 0 secs 
to clean immediately
+    private static final int MAX_OUTSTANDING_PUB_MESSAGES = 500;
+    private final PulsarService pulsar;
+    private final Schema<ServiceUnitStateData> schema;
+    private final ConcurrentOpenHashMap<String, CompletableFuture<String>> 
getOwnerRequests;
+    private final String lookupServiceAddress;
+    // TODO: define BrokerRegistry
+    private final Semaphore outstandingCleanupTombstoneMessages;
+    private final ConcurrentOpenHashMap<String, CompletableFuture<Void>> 
cleanupJobs;
+    private final LeaderElectionService leaderElectionService;
+    private TableView<ServiceUnitStateData> tableview;
+    private Producer<ServiceUnitStateData> producer;
+    private ScheduledFuture<?> cleanupTasks;
+    private SessionEvent lastMetadataSessionEvent = SessionReestablished;
+    private long lastMetadataSessionEventTimestamp = 0;
+    private long inFlightStateWaitingTimeInMillis;
+    private long maxCleanupDelayTimeInSecs;
+    private long minCleanupDelayTimeInSecs;
+    // cleanup metrics
+    private long totalCleanupCnt = 0;
+    private long totalBrokerCleanupTombstoneCnt = 0;
+    private long totalServiceUnitCleanupTombstoneCnt = 0;
+    private long totalServiceUnitCleanupErrorCnt = 0;
+    private long totalCleanupScheduledCnt = 0;
+    private long totalCleanupIgnoredCnt = 0;
+    private long totalCleanupCancelledCnt = 0;
+    private volatile ChannelState channelState;
+
+    enum ChannelState {
+        Closed(0),
+        Constructed(1),
+        LeaderElectionServiceStarted(2),
+        Started(3);
+
+        ChannelState(int id) {
+            this.id = id;
+        }
+        int id;
+    }
+
+    enum MetadataState {
+        Stable,
+        Jittery,
+        Unstable
+    }
+
+    public ServiceUnitStateChannelImpl(PulsarService pulsar) {
+        this.pulsar = pulsar;
+        this.lookupServiceAddress = pulsar.getLookupServiceAddress();
+        this.schema = Schema.JSON(ServiceUnitStateData.class);
+        this.outstandingCleanupTombstoneMessages = new 
Semaphore(MAX_OUTSTANDING_PUB_MESSAGES);
+        this.getOwnerRequests = ConcurrentOpenHashMap.<String,
+                CompletableFuture<String>>newBuilder().build();
+        this.cleanupJobs = ConcurrentOpenHashMap.<String, 
CompletableFuture<Void>>newBuilder().build();
+        this.inFlightStateWaitingTimeInMillis = 
MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS;
+        this.maxCleanupDelayTimeInSecs = MAX_CLEAN_UP_DELAY_TIME_IN_SECS;
+        this.minCleanupDelayTimeInSecs = MIN_CLEAN_UP_DELAY_TIME_IN_SECS;
+        this.leaderElectionService = new LeaderElectionService(
+                pulsar.getCoordinationService(), 
pulsar.getSafeWebServiceAddress(),
+                state -> {
+                    if (state == LeaderElectionState.Leading) {
+                        log.debug("This broker:{} is the leader now.", 
lookupServiceAddress);
+                        // TODO: schedule monitorOwnerships by brokerRegistry
+                    } else {
+                        log.debug("This broker:{} is a follower now.", 
lookupServiceAddress);
+                        // TODO: cancel scheduled monitorOwnerships if any
+                    }
+                });
+        this.channelState = Constructed;
+    }
+
+    public synchronized void start() throws PulsarServerException {
+        validateChannelState(LeaderElectionServiceStarted, false);
+        try {
+            leaderElectionService.start();
+            this.channelState = LeaderElectionServiceStarted;
+            log.debug("Successfully started the channel leader election 
service.");
+
+            if (producer != null) {
+                producer.close();
+                log.debug("Closed the channel producer.");
+            }
+            producer = pulsar.getClient().newProducer(schema)
+                    .enableBatching(true)
+                    .topic(TOPIC)
+                    .create();
+
+            log.debug("Successfully started the channel producer.");
+
+            if (tableview != null) {
+                tableview.close();
+                log.debug("Closed the channel tableview.");
+            }
+            tableview = pulsar.getClient().newTableViewBuilder(schema)
+                    .topic(TOPIC)
+                    // TODO: enable CompactionStrategy
+                    .create();
+            // TODO: schedule listen instead of foreachAndListen
+            tableview.forEachAndListen((key, value) -> handle(key, value));
+            log.debug("Successfully started the channel tableview.");
+
+            
pulsar.getLocalMetadataStore().registerSessionListener(this::handleMetadataSessionEvent);
+            log.debug("Successfully registered the 
handleMetadataSessionEvent");
+
+            channelState = Started;
+            log.info("Successfully started the channel.");
+        } catch (Exception e) {
+            String msg = "Failed to start the channel.";
+            log.error(msg, e);
+            throw new PulsarServerException(msg, e);
+        }
+    }
+
+    public synchronized void close() throws PulsarServerException {
+        channelState = Closed;
+        try {
+            leaderElectionService.close();
+            log.debug("Successfully closed the channel leader election 
service.");
+
+            if (tableview != null) {
+                tableview.close();
+                tableview = null;
+                log.debug("Successfully closed the channel tableview.");
+            }
+
+            if (producer != null) {
+                producer.close();
+                producer = null;
+                log.info("Successfully closed the channel producer.");
+            }
+
+            // TODO: clean brokerRegistry
+
+            if (cleanupTasks != null) {
+                cleanupTasks.cancel(true);
+                cleanupTasks = null;
+                log.info("Successfully cancelled the cleanup tasks");
+            }
+
+            log.info("Successfully closed the channel.");
+
+        } catch (Exception e) {
+            String msg = "Failed to close the channel.";
+            log.error(msg, e);
+            throw new PulsarServerException(msg, e);
+        }
+    }
+
+    private void validateChannelState(ChannelState targetState, boolean 
checkLowerIds) {
+        int order = checkLowerIds ? -1 : 1;
+        if (Integer.compare(channelState.id, targetState.id) * order > 0) {
+            throw new IllegalStateException("Invalid channel state:" + 
channelState.name());
+        }
+    }
+
+    public synchronized void scheduleCompaction() throws PulsarServerException 
{
+        try {
+            Long threshold = pulsar.getAdminClient().topicPolicies()
+                    .getCompactionThreshold(TOPIC);
+            if (threshold == null || threshold == 0) {
+                pulsar.getAdminClient().topicPolicies()
+                        .setCompactionThreshold(TOPIC, COMPACTION_THRESHOLD);
+                log.info("Scheduled compaction on topic:{}, threshold:{} 
bytes", TOPIC, COMPACTION_THRESHOLD);
+            } else {
+                log.info("Already set compaction on topic:{}, threshold:{} 
bytes", TOPIC, COMPACTION_THRESHOLD);

Review Comment:
   ```suggestion
                   log.info("Already set compaction on topic:{}, threshold:{} 
bytes", TOPIC, threshold);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to