Skip to content

Commit b52cc12

Browse files
Merge pull request #88 from PyCalendar/fix/v2.0.0-cyrus-regressions
Fix v2.0.0 regressions against current Cyrus
2 parents 3d0ea08 + 826636c commit b52cc12

13 files changed

Lines changed: 808 additions & 172 deletions
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``accept_invitation``/``decline_invitation``/``tentatively_accept`` no longer crash with ``AttributeError`` when an event has no ``participants`` property at all. They now raise ``JMAPMethodError`` with ``notFound``, as documented.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``get_address_books`` now marks an account's sole address book as default when the server reports none as default. Cyrus omits ``isDefault`` entirely instead of sending ``false``, so the one address book an account actually has was never flagged default.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``create_event``/``update_event`` now retry with the other ``recurrenceRule``/``recurrenceRules`` spelling when the server rejects the one they sent. Current Cyrus requires the plural array form. Stalwart still requires the singular form, so no single hardcoded spelling could satisfy both servers.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``ical_to_jscal`` now emits a ``sendTo`` property on every participant, alongside the existing ``calendarAddress``. Current Cyrus rejects any participant without ``sendTo``, on both create and update, regardless of scheduling messages.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``ical_to_jscal`` no longer emits a ``version`` property on created/updated events. Current Cyrus rejects it outright with ``invalidProperties``. RFC 8984 marks the property optional, so leaving it out is correct.

‎src/calendaring_jmap/_methods/contact.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,18 @@ def parse_address_book_get(response_args: dict) -> list[JMAPAddressBook]:
5050
List of ``JMAPAddressBook``.
5151
Empty if ``"list"`` is absent or empty.
5252
"""
53-
return [JMAPAddressBook.from_jmap(item) for item in response_args.get("list", [])]
53+
books = [JMAPAddressBook.from_jmap(item) for item in response_args.get("list", [])]
54+
# RFC 9610 section 2 requires isDefault to be present and true for
55+
# exactly one AddressBook in the account; confirmed live that Cyrus's
56+
# current image omits the key entirely rather than sending it false,
57+
# which JMAPAddressBook.from_jmap otherwise reads as "not default" even
58+
# for the account's only address book. When there is exactly one
59+
# AddressBook and none of them actually claimed isDefault, it is the de
60+
# facto default regardless of what the server sent, so mark it rather
61+
# than reporting a default-less account the spec says can't happen.
62+
if len(books) == 1 and not books[0].is_default:
63+
books[0].is_default = True
64+
return books
5465

5566

5667
def build_contact_query(

‎src/calendaring_jmap/async_client.py‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -455,13 +455,17 @@ async def _create_event_impl(
455455
jscal = self._strip_server_managed_event_properties(event)
456456
self._resolve_create_calendar_ids(jscal, calendar_id)
457457
target_account = self._resolve_account(session, account_id)
458-
call = build_event_set_create(
459-
target_account,
460-
{"new-0": jscal},
461-
send_scheduling_messages=send_scheduling_messages,
462-
if_in_state=if_in_state,
463-
)
464-
responses = await self._request([call])
458+
tried_recurrence_rule_keys: set[str] = set()
459+
while True:
460+
call = build_event_set_create(
461+
target_account,
462+
{"new-0": jscal},
463+
send_scheduling_messages=send_scheduling_messages,
464+
if_in_state=if_in_state,
465+
)
466+
responses = await self._request([call])
467+
if not self._retry_recurrence_rule_create(responses, jscal, tried_recurrence_rule_keys):
468+
break
465469
event_id = self._parse_create_response(
466470
responses, session.api_url, "CalendarEvent/set", parse_event_set
467471
)
@@ -784,15 +788,21 @@ async def update_event(
784788
session = await self._get_session()
785789
target_account = self._resolve_account(session, account_id)
786790
patch, nulled = self._build_event_update_patch(event)
791+
tried_recurrence_rule_keys: set[str] = set()
787792
while True:
788793
responses = await self._request(
789794
[build_event_set_update(target_account, {event_id: patch}, if_in_state=if_in_state)]
790795
)
791796
drop = self._unsupported_null_keys(responses, event_id, patch, nulled)
792-
if not drop:
793-
break
794-
for key in drop:
795-
patch.pop(key, None)
797+
if drop:
798+
for key in drop:
799+
patch.pop(key, None)
800+
continue
801+
if self._retry_recurrence_rule_update(
802+
responses, event_id, patch, tried_recurrence_rule_keys
803+
):
804+
continue
805+
break
796806
self._parse_update_response(
797807
responses, session.api_url, "CalendarEvent/set", parse_event_set, event_id
798808
)

‎src/calendaring_jmap/client.py‎

Lines changed: 174 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -554,14 +554,19 @@ def _unsupported_null_keys(
554554
new iCalendar, so we report it as droppable, letting the caller
555555
retry the update without it.
556556
557-
Returns the set of droppable keys when the failure is exactly this case,
558-
or ``None`` when the update succeeded or failed for a genuine reason (in
559-
which case the caller proceeds to ``_parse_update_response``,
560-
which raises the real error). Some servers report only one offending
561-
property per response, so the caller retries in a loop, dropping the
562-
reported keys until the update succeeds or hits a genuine error; each
563-
returned key is guaranteed still present in ``patch``, so the loop
564-
strictly shrinks the patch and terminates.
557+
Returns the set of droppable keys when every offending property not
558+
accounted for by this check is one of ``_RECURRENCE_RULE_KEYS`` (left
559+
for ``_retry_recurrence_rule_update`` to handle in the same retry
560+
pass, since a server can reject both a stale null-cleanup key and
561+
the wrong recurrenceRule/recurrenceRules spelling in one response,
562+
confirmed live), or ``None`` when the update succeeded or failed for
563+
a genuine reason (in which case the caller proceeds to
564+
``_parse_update_response``, which raises the real error). Some
565+
servers report only one offending property per response, so the
566+
caller retries in a loop, dropping the reported keys until the
567+
update succeeds or hits a genuine error; each returned key is
568+
guaranteed still present in ``patch``, so the loop strictly shrinks
569+
the patch and terminates.
565570
"""
566571
for method_name, resp_args, _ in responses:
567572
if method_name == "CalendarEvent/set":
@@ -571,14 +576,142 @@ def _unsupported_null_keys(
571576
return None
572577
props = set(err.get("properties") or [])
573578
droppable = {p for p in props if p in nulled and p in patch and patch[p] is None}
574-
# Only retry when every offending property is null-cleanup we can
575-
# safely omit; if the client actually set one of them to a value,
576-
# the rejection is genuine and must surface.
577-
if props and props == droppable:
579+
unexplained = props - droppable
580+
# Only retry when every offending property is either
581+
# null-cleanup we can safely omit, or a recurrenceRule/
582+
# recurrenceRules spelling mismatch left for the other retry
583+
# helper; if the client actually set some other property to
584+
# a real value, the rejection is genuine and must surface.
585+
if props and unexplained <= _JMAPClientBase._RECURRENCE_RULE_KEYS_SET:
578586
return droppable
579587
return None
580588
return None
581589

590+
_RECURRENCE_RULE_KEYS = ("recurrenceRule", "recurrenceRules")
591+
_RECURRENCE_RULE_KEYS_SET = frozenset(_RECURRENCE_RULE_KEYS)
592+
593+
@staticmethod
594+
def _try_recurrence_rule_fallback_key(err: dict | None, jscal: dict, tried: set[str]) -> bool:
595+
"""Detect a create/update rejected solely for using the wrong
596+
``recurrenceRule``/``recurrenceRules`` spelling, and if so, swap
597+
``jscal`` in place to the other spelling so the caller can retry.
598+
599+
RFC 8984 section 4.3.3 defines the plural, array-valued
600+
``recurrenceRules``; the singular ``recurrenceRule`` is an older,
601+
non-normative spelling some servers still expect instead. Verified
602+
live against both test servers this project targets: Cyrus's
603+
current image requires the plural array and rejects the singular
604+
with ``invalidProperties``, while Stalwart requires the singular
605+
and rejects the plural the same way. Since neither server accepts
606+
both spellings in the same request (also verified live) and which
607+
one a given server wants is not otherwise discoverable, the caller
608+
sends whichever spelling ``jscal`` already uses, and on a rejection
609+
naming exactly that one property, swaps to the other spelling and
610+
retries once.
611+
612+
``tried`` starts as an empty set the caller owns across its whole
613+
retry loop; the one spelling this function ever swaps to is added
614+
to it before returning, so a server that rejects both spellings in
615+
turn (never actually observed, but not provable impossible from
616+
one response alone) gets exactly one swap, not an alternating
617+
retry forever: since there are only two possible spellings, having
618+
already swapped once means every spelling has now been sent.
619+
620+
Returns ``True`` (and mutates ``jscal``) when ``err`` is an
621+
``invalidProperties`` rejection naming exactly one of
622+
``_RECURRENCE_RULE_KEYS`` that is also the key actually present in
623+
``jscal``, and no swap has happened yet this retry loop, or
624+
``False`` (``jscal`` untouched) when the failure is unrelated (a
625+
different property, more than one offending property, a spelling
626+
already swapped to once this loop, or no error at all) and should
627+
surface as-is.
628+
"""
629+
if tried or not err or err.get("type") != "invalidProperties":
630+
return False
631+
props = set(err.get("properties") or [])
632+
if len(props) != 1:
633+
return False
634+
(offending,) = props
635+
if offending not in _JMAPClientBase._RECURRENCE_RULE_KEYS or offending not in jscal:
636+
return False
637+
fallback = next(k for k in _JMAPClientBase._RECURRENCE_RULE_KEYS if k != offending)
638+
value = jscal[offending]
639+
# "recurrenceRule" (singular) is one RecurrenceRule object;
640+
# "recurrenceRules" (plural, RFC 8984 section 4.3.3) is an array of
641+
# them, since an event can in principle have more than one RRULE.
642+
# Swapping the key alone would send an object where the other
643+
# spelling expects an array, or vice versa, so the value's shape
644+
# is converted along with the key: wrap a lone object in a
645+
# one-element list going singular to plural. Going plural to
646+
# singular, an empty list has nothing to convert (leave jscal
647+
# untouched, same as any other unhandled case); otherwise only the
648+
# first rule survives if the caller actually supplied more than one
649+
# (ical_to_jscal itself never does; a caller building its own
650+
# CalendarEvent dict directly could), matching this project's own
651+
# established "log and keep first" tradeoff for the same case in
652+
# ical_to_jscal's own RRULE handling, since the singular spelling
653+
# has no way to carry more than one.
654+
if fallback == "recurrenceRules":
655+
value = [value]
656+
elif isinstance(value, list):
657+
if not value:
658+
return False
659+
if len(value) > 1:
660+
log.warning(
661+
"create_event()/update_event(): server rejected the plural "
662+
"recurrenceRules spelling and only the singular is accepted; "
663+
"%d rules were given, only the first is kept.",
664+
len(value),
665+
)
666+
value = value[0]
667+
tried.add(fallback)
668+
del jscal[offending]
669+
jscal[fallback] = value
670+
return True
671+
672+
@staticmethod
673+
def _recurrence_rule_set_error(
674+
responses: list,
675+
) -> tuple[dict, dict, list[str], dict, dict, dict] | None:
676+
"""Find the first ``CalendarEvent/set`` response in ``responses``
677+
and return its parsed 6-tuple, or ``None`` if there is none.
678+
679+
Shared by ``_retry_recurrence_rule_create``/``_retry_recurrence_rule_update``,
680+
which otherwise differ only in which element of the tuple holds the
681+
error to check (``not_created["new-0"]`` vs. ``not_updated[event_id]``).
682+
"""
683+
for method_name, resp_args, _ in responses:
684+
if method_name == "CalendarEvent/set":
685+
return parse_event_set(resp_args)
686+
return None
687+
688+
@staticmethod
689+
def _retry_recurrence_rule_create(responses: list, jscal: dict, tried: set[str]) -> bool:
690+
"""``_try_recurrence_rule_fallback_key``, applied to a create
691+
response's ``not_created["new-0"]`` error instead of an update's
692+
``not_updated``."""
693+
parsed = _JMAPClientBase._recurrence_rule_set_error(responses)
694+
if parsed is None:
695+
return False
696+
_, _, _, not_created, _, _ = parsed
697+
return _JMAPClientBase._try_recurrence_rule_fallback_key(
698+
not_created.get("new-0"), jscal, tried
699+
)
700+
701+
@staticmethod
702+
def _retry_recurrence_rule_update(
703+
responses: list, event_id: str, patch: dict, tried: set[str]
704+
) -> bool:
705+
"""``_try_recurrence_rule_fallback_key``, applied to an update
706+
response's ``not_updated[event_id]`` error."""
707+
parsed = _JMAPClientBase._recurrence_rule_set_error(responses)
708+
if parsed is None:
709+
return False
710+
_, _, _, _, not_updated, _ = parsed
711+
return _JMAPClientBase._try_recurrence_rule_fallback_key(
712+
not_updated.get(event_id), patch, tried
713+
)
714+
582715
# ---------------------------------------------------------------------------
583716
# Shared response parsers, pure synchronous, used by both sync and async
584717
# clients. Each method takes the raw ``methodResponses`` list returned by
@@ -713,7 +846,7 @@ def _participant_matches_email(participant: dict, email: str) -> bool:
713846

714847
@staticmethod
715848
def _find_participant_id_by_email(
716-
participants: dict, own_email: str, api_url: str, event_id: str
849+
participants: dict | None, own_email: str, api_url: str, event_id: str
717850
) -> str:
718851
"""Return the id of the entry in ``participants`` whose email is ``own_email``.
719852
@@ -722,10 +855,16 @@ def _find_participant_id_by_email(
722855
Shared by ``JMAPClient._find_own_participant_id`` and
723856
``AsyncJMAPClient._find_own_participant_id``.
724857
858+
``participants`` is ``None`` for an event with no ``participants``
859+
property at all (RFC 8984 section 4.4.6: optional, omitted rather
860+
than an empty map when there are none), treated the same as an
861+
empty map: no participant can match, so this still raises rather
862+
than crashing on ``None.items()``.
863+
725864
Raises:
726865
JMAPMethodError: If no participant matches ``own_email``.
727866
"""
728-
for participant_id, participant in participants.items():
867+
for participant_id, participant in (participants or {}).items():
729868
if _JMAPClientBase._participant_matches_email(participant, own_email):
730869
return participant_id
731870
raise JMAPMethodError(
@@ -1532,13 +1671,17 @@ def _create_event_impl(
15321671
jscal = self._strip_server_managed_event_properties(event)
15331672
self._resolve_create_calendar_ids(jscal, calendar_id)
15341673
target_account = self._resolve_account(session, account_id)
1535-
call = build_event_set_create(
1536-
target_account,
1537-
{"new-0": jscal},
1538-
send_scheduling_messages=send_scheduling_messages,
1539-
if_in_state=if_in_state,
1540-
)
1541-
responses = self._request([call])
1674+
tried_recurrence_rule_keys: set[str] = set()
1675+
while True:
1676+
call = build_event_set_create(
1677+
target_account,
1678+
{"new-0": jscal},
1679+
send_scheduling_messages=send_scheduling_messages,
1680+
if_in_state=if_in_state,
1681+
)
1682+
responses = self._request([call])
1683+
if not self._retry_recurrence_rule_create(responses, jscal, tried_recurrence_rule_keys):
1684+
break
15421685
event_id = self._parse_create_response(
15431686
responses, session.api_url, "CalendarEvent/set", parse_event_set
15441687
)
@@ -1987,15 +2130,21 @@ def update_event(
19872130
session = self._get_session()
19882131
target_account = self._resolve_account(session, account_id)
19892132
patch, nulled = self._build_event_update_patch(event)
2133+
tried_recurrence_rule_keys: set[str] = set()
19902134
while True:
19912135
responses = self._request(
19922136
[build_event_set_update(target_account, {event_id: patch}, if_in_state=if_in_state)]
19932137
)
19942138
drop = self._unsupported_null_keys(responses, event_id, patch, nulled)
1995-
if not drop:
1996-
break
1997-
for key in drop:
1998-
patch.pop(key, None)
2139+
if drop:
2140+
for key in drop:
2141+
patch.pop(key, None)
2142+
continue
2143+
if self._retry_recurrence_rule_update(
2144+
responses, event_id, patch, tried_recurrence_rule_keys
2145+
):
2146+
continue
2147+
break
19992148
self._parse_update_response(
20002149
responses, session.api_url, "CalendarEvent/set", parse_event_set, event_id
20012150
)

0 commit comments

Comments
 (0)