+# uo2m: UID Offset to MSN, this is an arrayref by default,
+# but uo2m_hibernate can compact and deduplicate it
+sub uo2m_ary_new ($;$) {
+ my ($self, $exists) = @_;
+ my $base = $self->{uid_base};
+ my $uids = $self->{ibx}->over->uid_range($base + 1, $base + UID_SLICE);
+
+ # convert UIDs to offsets from {base}
+ my @tmp; # [$UID_OFFSET] => $MSN
+ my $msn = 0;
+ ++$base;
+ $tmp[$_ - $base] = ++$msn for @$uids;
+ $$exists = $msn if $exists;
+ \@tmp;
+}
+
+# changes UID-offset-to-MSN mapping into a deduplicated scalar:
+# uint16_t uo2m[UID_SLICE].
+# May be swapped out for idle clients if THP is disabled.
+sub uo2m_hibernate ($) {
+ my ($self) = @_;
+ ref(my $uo2m = $self->{uo2m}) or return;
+ my %dedupe = ( uo2m_pack($uo2m) => undef );
+ $self->{uo2m} = (keys(%dedupe))[0];
+ undef;
+}
+
+sub uo2m_last_uid ($) {
+ my ($self) = @_;
+ defined(my $uo2m = $self->{uo2m}) or die 'BUG: uo2m_last_uid w/o {uo2m}';
+ (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
+}
+
+sub uo2m_pack ($) {
+ # $_[0] is an arrayref of MSNs, it may have undef gaps if there
+ # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
+ no warnings 'uninitialized';
+ pack('S*', @{$_[0]});
+}
+
+# extend {uo2m} to account for new messages which arrived since
+# {uo2m} was created.
+sub uo2m_extend ($$;$) {
+ my ($self, $new_uid_max) = @_;
+ defined(my $uo2m = $self->{uo2m}) or
+ return($self->{uo2m} = uo2m_ary_new($self));
+ my $beg = uo2m_last_uid($self); # last UID we've learned
+ return $uo2m if $beg >= $new_uid_max; # fast path
+
+ # need to extend the current range:
+ my $base = $self->{uid_base};
+ ++$beg;
+ my $uids = $self->{ibx}->over->uid_range($beg, $base + UID_SLICE);
+ return $uo2m if !scalar(@$uids);
+ my @tmp; # [$UID_OFFSET] => $MSN
+ my $write_method = $_[2] // 'msg_more';
+ if (ref($uo2m)) {
+ my $msn = $uo2m->[-1];
+ $tmp[$_ - $beg] = ++$msn for @$uids;
+ $self->$write_method("* $msn EXISTS\r\n");
+ push @$uo2m, @tmp;
+ $uo2m;
+ } else {
+ my $msn = unpack('S', substr($uo2m, -2, 2));
+ $tmp[$_ - $beg] = ++$msn for @$uids;
+ $self->$write_method("* $msn EXISTS\r\n");
+ $uo2m .= uo2m_pack(\@tmp);
+ my %dedupe = ($uo2m => undef);
+ $self->{uo2m} = (keys %dedupe)[0];
+ }
+}
+
+sub cmd_noop ($$) {
+ my ($self, $tag) = @_;
+ defined($self->{uid_base}) and
+ uo2m_extend($self, $self->{uid_base} + UID_SLICE);
+ \"$tag OK Noop done\r\n";
+}
+
+# the flexible version which works on scalars and array refs.
+# Must call uo2m_extend before this
+sub uid2msn ($$) {
+ my ($self, $uid) = @_;
+ my $uo2m = $self->{uo2m};
+ my $off = $uid - $self->{uid_base} - 1;
+ ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
+}
+
+# returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
+# $msn2uid->[$MSN-1] => $UID. The result of this is always ephemeral
+# and does not live beyond the event loop.
+sub msn2uid ($) {
+ my ($self) = @_;
+ my $base = $self->{uid_base};
+ my $uo2m = uo2m_extend($self, $base + UID_SLICE);
+ $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
+
+ my $uo = 0;
+ my @msn2uid;
+ for my $msn (@$uo2m) {
+ ++$uo;
+ $msn2uid[$msn - 1] = $uo + $base if $msn;
+ }
+ \@msn2uid;
+}
+
+# converts a set of message sequence numbers in requests to UIDs:
+sub msn_to_uid_range ($$) {
+ my $msn2uid = $_[0];
+ $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] // 0 + 1)!sge;
+}
+
+# called by PublicInbox::InboxIdle
+sub on_inbox_unlock {
+ my ($self, $ibx) = @_;
+ my $uid_end = $self->{uid_base} + UID_SLICE;
+ uo2m_extend($self, $uid_end, 'write');
+ my $new = uo2m_last_uid($self);
+ if ($new == $uid_end) { # max exceeded $uid_end
+ # continue idling w/o inotify
+ my $sock = $self->{sock} or return;
+ $ibx->unsubscribe_unlock(fileno($sock));
+ }
+}
+
+# called every X minute(s) or so by PublicInbox::DS::later
+my $IDLERS = {};
+my $idle_timer;
+sub idle_tick_all {
+ my $old = $IDLERS;
+ $IDLERS = {};
+ for my $i (values %$old) {
+ next if ($i->{wbuf} || !exists($i->{-idle_tag}));
+ $i->update_idle_time or next;
+ $IDLERS->{fileno($i->{sock})} = $i;
+ $i->write(\"* OK Still here\r\n");
+ }
+ $idle_timer = scalar keys %$IDLERS ?
+ PublicInbox::DS::later(\&idle_tick_all) : undef;
+}
+
+sub cmd_idle ($$) {
+ my ($self, $tag) = @_;
+ # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
+ my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
+ my $uid_end = $self->{uid_base} + UID_SLICE;
+ uo2m_extend($self, $uid_end);
+ my $sock = $self->{sock} or return;
+ my $fd = fileno($sock);
+ $self->{-idle_tag} = $tag;
+ # only do inotify on most recent slice
+ if ($ibx->over->max < $uid_end) {
+ $ibx->subscribe_unlock($fd, $self);
+ $self->{imapd}->idler_start;
+ }
+ $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
+ $IDLERS->{$fd} = $self;
+ \"+ idling\r\n"
+}
+
+sub stop_idle ($$) {
+ my ($self, $ibx) = @_;
+ my $sock = $self->{sock} or return;
+ my $fd = fileno($sock);
+ delete $IDLERS->{$fd};
+ $ibx->unsubscribe_unlock($fd);
+}
+
+sub idle_done ($$) {
+ my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
+ defined(my $idle_tag = delete $self->{-idle_tag}) or
+ return "$tag BAD not idle\r\n";
+ my $ibx = $self->{ibx} or do {
+ warn "BUG: idle_tag set w/o inbox";
+ return "$tag BAD internal bug\r\n";
+ };
+ stop_idle($self, $ibx);
+ "$idle_tag OK Idle done\r\n";
+}
+
+sub ensure_slices_exist ($$$) {
+ my ($imapd, $ibx, $max) = @_;
+ defined(my $mb_top = $ibx->{newsgroup}) or return;
+ my $mailboxes = $imapd->{mailboxes};
+ my @created;
+ for (my $i = int($max/UID_SLICE); $i >= 0; --$i) {
+ my $sub_mailbox = "$mb_top.$i";
+ last if exists $mailboxes->{$sub_mailbox};
+ $mailboxes->{$sub_mailbox} = $ibx;
+ $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
+ push @created, $sub_mailbox;
+ }
+ return unless @created;
+ my $l = $imapd->{inboxlist} or return;
+ push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
+}
+
+sub inbox_lookup ($$;$) {
+ my ($self, $mailbox, $examine) = @_;
+ my ($ibx, $exists, $uidmax, $uid_base) = (undef, 0, 0, 0);
+ $mailbox = lc $mailbox;
+ $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
+ my $over = $ibx->over;
+ if ($over != $ibx) { # not a dummy
+ $mailbox =~ /\.([0-9]+)\z/ or
+ die "BUG: unexpected dummy mailbox: $mailbox\n";
+ $uid_base = $1 * UID_SLICE;
+
+ # ->num_highwater caches for writers, so use ->meta_accessor
+ $uidmax = $ibx->mm->meta_accessor('num_highwater') // 0;
+ if ($examine) {
+ $self->{uid_base} = $uid_base;
+ $self->{ibx} = $ibx;
+ $self->{uo2m} = uo2m_ary_new($self, \$exists);
+ } else {
+ $exists = $over->imap_exists;
+ }
+ ensure_slices_exist($self->{imapd}, $ibx, $over->max);
+ } else {
+ if ($examine) {
+ $self->{uid_base} = $uid_base;
+ $self->{ibx} = $ibx;
+ delete $self->{uo2m};
+ }
+ # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
+ # check for new UID ranges (e.g. "INBOX.foo.bar.1")
+ if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
+ ensure_slices_exist($self->{imapd}, $z, $z->over->max);
+ }
+ }
+ ($ibx, $exists, $uidmax + 1, $uid_base);
+}