@@ -35,26 +35,47 @@ public static void main(String[] args) {
3535 .useTransportSecurity () // if not using TLS, replace with .usePlaintext()
3636 .build ();
3737
38- try {
39- WatchRequest request = WatchRequest .
40- newBuilder ()
41- .addOptionalUpdateKinds (com .authzed .api .v1 .WatchKind .WATCH_KIND_INCLUDE_CHECKPOINTS )
42- .build ();
43-
44- Iterator <WatchResponse > watchStream = watchClient .watch (request );
45-
46- while (watchStream .hasNext ()) {
47- WatchResponse msg = watchStream .next ();
48- if (msg .getUpdatesCount () > 0 ) {
49- for (var update : msg .getUpdatesList ()) {
50- System .out .println ("Received update: " + update );
38+ ZedToken lastZedToken = ZedToken .newBuilder ().setToken ("" ).build ();
39+
40+ while (true ) {
41+ try {
42+ WatchRequest .Builder builder = WatchRequest .newBuilder ()
43+ .addOptionalUpdateKinds (com .authzed .api .v1 .WatchKind .WATCH_KIND_INCLUDE_CHECKPOINTS );
44+
45+ if (!lastZedToken .getToken ().isEmpty ()) {
46+ System .out .println ("Resuming watch from token: " + lastZedToken .getToken ());
47+ builder .setOptionalStartCursor (lastZedToken );
48+ }
49+
50+ WatchRequest request = builder .build ();
51+
52+ Iterator <WatchResponse > watchStream = watchClient .watch (request );
53+
54+ while (watchStream .hasNext ()) {
55+ WatchResponse msg = watchStream .next ();
56+
57+ if (msg .getUpdatesCount () > 0 ) {
58+ for (var update : msg .getUpdatesList ()) {
59+ System .out .println ("Received update: " + update );
60+ }
61+ } else {
62+ System .out .println ("No changes made in SpiceDB" );
63+ }
64+
65+ if (!msg .getChangesThrough ().getToken ().isEmpty ()) {
66+ lastZedToken = msg .getChangesThrough ();
5167 }
68+ }
69+
70+ } catch (Exception e ) {
71+ if (e instanceof StatusRuntimeException sre && (sre .getStatus ().getCode ().equals (Status .UNAVAILABLE .getCode ()) ||
72+ (sre .getStatus ().getCode ().equals (Status .INTERNAL .getCode ())) && sre .getMessage ().contains ("stream timeout" ))) {
73+ // Probably a server restart. Retry.
5274 } else {
53- System .out .println ("No changes made in SpiceDB" );
75+ System .out .println ("Error calling watch: " + e .getMessage ());
76+ return ;
5477 }
5578 }
56- } catch (Exception e ) {
57- System .out .println ("Error calling watch: " + e .getMessage ());
5879 }
5980 }
6081}
0 commit comments