diff --git a/CodenameOne/src/com/codename1/annotations/grpc/GrpcClient.java b/CodenameOne/src/com/codename1/annotations/grpc/GrpcClient.java index 08c847e0d0a..b12325c433d 100644 --- a/CodenameOne/src/com/codename1/annotations/grpc/GrpcClient.java +++ b/CodenameOne/src/com/codename1/annotations/grpc/GrpcClient.java @@ -6,6 +6,19 @@ * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.annotations.grpc; @@ -15,11 +28,14 @@ import java.lang.annotation.Target; /// Marks an interface as a gRPC client that the build-time annotation -/// processor wires up to a generated gRPC-Web implementation. Each +/// processor wires up to a generated implementation: gRPC-Web in an +/// application, native gRPC over HTTP/2 in a backend. Each /// abstract method must carry an [Rpc] annotation naming the gRPC /// method, and at most one non-callback parameter -- the request -/// message, a `@ProtoMessage`-annotated POJO. The final parameter is -/// an `OnComplete>` callback. +/// message, a `@ProtoMessage`-annotated POJO. In an application the +/// final parameter is an `OnComplete>` +/// callback; in a backend methods are blocking and may stream (see the +/// backend's `com.codename1.backend.grpc` package). /// /// The fully qualified service path defaults to /// `/` -- for example @@ -28,12 +44,14 @@ /// interface-level default. /// /// The processor emits a `Impl` class in generated-sources -/// and registers it with [com.codename1.io.grpc.GrpcClients] so the +/// and registers it with the runtime's client registry +/// (`com.codename1.io.grpc.GrpcClients` in an application) so the /// interface's `static T of(String baseUrl)` factory can return an /// instance without the project source referencing the impl directly. -/// Mirrors [com.codename1.annotations.rest.RestClient]. +/// Mirrors `com.codename1.annotations.rest.RestClient`. @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) +@com.codename1.impl.SharedWithBackend public @interface GrpcClient { /// Fully qualified gRPC service path (without leading slash), e.g. /// `helloworld.Greeter`. Combined with each method's [Rpc#value()] diff --git a/CodenameOne/src/com/codename1/annotations/grpc/ProtoEnum.java b/CodenameOne/src/com/codename1/annotations/grpc/ProtoEnum.java index ff451e06896..872bc77823d 100644 --- a/CodenameOne/src/com/codename1/annotations/grpc/ProtoEnum.java +++ b/CodenameOne/src/com/codename1/annotations/grpc/ProtoEnum.java @@ -6,6 +6,19 @@ * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.annotations.grpc; @@ -27,5 +40,6 @@ /// the field is absent. @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) +@com.codename1.impl.SharedWithBackend public @interface ProtoEnum { } diff --git a/CodenameOne/src/com/codename1/annotations/grpc/ProtoField.java b/CodenameOne/src/com/codename1/annotations/grpc/ProtoField.java index 18975acce6d..1c6064c6e0b 100644 --- a/CodenameOne/src/com/codename1/annotations/grpc/ProtoField.java +++ b/CodenameOne/src/com/codename1/annotations/grpc/ProtoField.java @@ -6,6 +6,19 @@ * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.annotations.grpc; @@ -28,6 +41,7 @@ /// `fixed32` / `fixed64` in proto3). @Retention(RetentionPolicy.CLASS) @Target(ElementType.FIELD) +@com.codename1.impl.SharedWithBackend public @interface ProtoField { /// Protobuf field tag (positive integer, unique per message). int tag(); diff --git a/CodenameOne/src/com/codename1/annotations/grpc/ProtoMessage.java b/CodenameOne/src/com/codename1/annotations/grpc/ProtoMessage.java index 0acdeb048da..ddbf960584b 100644 --- a/CodenameOne/src/com/codename1/annotations/grpc/ProtoMessage.java +++ b/CodenameOne/src/com/codename1/annotations/grpc/ProtoMessage.java @@ -6,6 +6,19 @@ * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.annotations.grpc; @@ -29,10 +42,11 @@ /// `@ProtoEnum`-marked enums, or `java.util.List` of any of the /// above (interpreted as `repeated` in proto3). /// -/// Mirrors the design of [com.codename1.annotations.Mapped] for JSON +/// Mirrors the design of `com.codename1.annotations.Mapped` for JSON /// projection; you can carry both annotations on the same class to /// support JSON and protobuf wire formats off the same POJO. @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) +@com.codename1.impl.SharedWithBackend public @interface ProtoMessage { } diff --git a/CodenameOne/src/com/codename1/annotations/grpc/Rpc.java b/CodenameOne/src/com/codename1/annotations/grpc/Rpc.java index aa4f585225d..7a490d4b538 100644 --- a/CodenameOne/src/com/codename1/annotations/grpc/Rpc.java +++ b/CodenameOne/src/com/codename1/annotations/grpc/Rpc.java @@ -6,6 +6,19 @@ * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.annotations.grpc; @@ -14,17 +27,20 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/// Binds a [GrpcClient] interface method to a gRPC unary RPC. The +/// Binds a method to a gRPC RPC: a [GrpcClient] interface method in an +/// application or a backend, or a method of a backend `@GrpcService`. The /// `value` is the gRPC method name (e.g. `SayHello`) and is combined /// with the interface-level [GrpcClient#value()] to form /// `//`. The optional [#service()] overrides the /// interface-level service path for a single method (useful when an /// interface aggregates calls into multiple services). /// -/// Streaming RPCs are not supported in this release -- only unary -/// (single request, single response). +/// Applications call unary RPCs only (gRPC-Web carries no client +/// streaming). A backend supports all four shapes; it infers the shape +/// from the method signature. @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) +@com.codename1.impl.SharedWithBackend public @interface Rpc { /// The gRPC method name as declared in the `.proto` `rpc` line, /// e.g. `SayHello`. Joined to the service path via `/`. diff --git a/CodenameOne/src/com/codename1/annotations/grpc/package-info.java b/CodenameOne/src/com/codename1/annotations/grpc/package-info.java index c4e2af4d4ce..b5e6d8e6b79 100644 --- a/CodenameOne/src/com/codename1/annotations/grpc/package-info.java +++ b/CodenameOne/src/com/codename1/annotations/grpc/package-info.java @@ -6,9 +6,22 @@ * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ /// gRPC-Web client annotations. [GrpcClient] marks an interface as a -/// gRPC client; [Rpc] binds each method to a unary RPC. +/// gRPC client; [Rpc] binds each method to an RPC. /// [ProtoMessage] marks a POJO as a protobuf message; /// [ProtoField] tags each field; [ProtoEnum] marks an enum as /// protobuf-encoded. diff --git a/CodenameOne/src/com/codename1/io/grpc/ProtoCodec.java b/CodenameOne/src/com/codename1/io/grpc/ProtoCodec.java index 620b6d2ea75..5d583a59d7f 100644 --- a/CodenameOne/src/com/codename1/io/grpc/ProtoCodec.java +++ b/CodenameOne/src/com/codename1/io/grpc/ProtoCodec.java @@ -6,6 +6,19 @@ * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.io.grpc; @@ -19,6 +32,7 @@ /// /// Implementations must be stateless -- the same codec instance is /// shared across concurrent requests. +@com.codename1.impl.SharedWithBackend public interface ProtoCodec { /// Writes `value`'s populated fields to `out` in the protobuf diff --git a/CodenameOne/src/com/codename1/io/grpc/ProtoCodecs.java b/CodenameOne/src/com/codename1/io/grpc/ProtoCodecs.java index fbd2abdb360..237dc1dec3a 100644 --- a/CodenameOne/src/com/codename1/io/grpc/ProtoCodecs.java +++ b/CodenameOne/src/com/codename1/io/grpc/ProtoCodecs.java @@ -6,6 +6,19 @@ * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.io.grpc; @@ -19,7 +32,8 @@ /// impls and per-class codecs call [#lookup(Class)] to resolve /// nested-message types at runtime. /// -/// Mirrors [com.codename1.io.rest.RestClients]. +/// Mirrors `com.codename1.io.rest.RestClients`. +@com.codename1.impl.SharedWithBackend public final class ProtoCodecs { private static final Map, ProtoCodec> REGISTRY = new HashMap, ProtoCodec>(); diff --git a/CodenameOne/src/com/codename1/io/grpc/ProtoReader.java b/CodenameOne/src/com/codename1/io/grpc/ProtoReader.java index 089e25d817e..033d3231bbd 100644 --- a/CodenameOne/src/com/codename1/io/grpc/ProtoReader.java +++ b/CodenameOne/src/com/codename1/io/grpc/ProtoReader.java @@ -6,6 +6,19 @@ * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.io.grpc; @@ -23,6 +36,7 @@ /// field number, and call the appropriate `readXxx` method. Unknown /// fields are passed to [#skipField(int)] -- the same recovery /// behaviour `protoc`-generated code exhibits. +@com.codename1.impl.SharedWithBackend public final class ProtoReader { private final byte[] buf; diff --git a/CodenameOne/src/com/codename1/io/grpc/ProtoWriter.java b/CodenameOne/src/com/codename1/io/grpc/ProtoWriter.java index 496106c919b..75f5605db0d 100644 --- a/CodenameOne/src/com/codename1/io/grpc/ProtoWriter.java +++ b/CodenameOne/src/com/codename1/io/grpc/ProtoWriter.java @@ -6,6 +6,19 @@ * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.io.grpc; @@ -28,6 +41,7 @@ /// | 1 | I64 | fixed64, sfixed64, double | /// | 2 | LEN | string, bytes, embedded messages, packed repeated | /// | 5 | I32 | fixed32, sfixed32, float | +@com.codename1.impl.SharedWithBackend public final class ProtoWriter { public static final int WIRE_VARINT = 0; diff --git a/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/Greeter.java b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/Greeter.java new file mode 100644 index 00000000000..5a7fc5375b3 --- /dev/null +++ b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/Greeter.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.backend.grpc; + +import com.codename1.annotations.grpc.Rpc; +import com.codename1.backend.annotations.GrpcService; +import com.codename1.backend.grpc.StreamObserver; +import java.util.Iterator; + +// tag::backend-grpc-service[] +@GrpcService("demo.Greeter") +public class Greeter { + @Rpc("SayHello") // unary + public HelloReply sayHello(HelloRequest request) { + return reply("Hello " + request.name); + } + + @Rpc("Countdown") // server streaming + public void countdown(HelloRequest request, StreamObserver out) { + for (int i = 3; i > 0; i--) { + out.onNext(reply(request.name + " " + i)); + } + } + + @Rpc("Collect") // client streaming + public HelloReply collect(Iterator requests) { + StringBuilder names = new StringBuilder(); + while (requests.hasNext()) { + names.append(requests.next().name).append(' '); + } + return reply(names.toString().trim()); + } + + @Rpc("Chat") // bidirectional streaming + public void chat(Iterator in, StreamObserver out) { + while (in.hasNext()) { + out.onNext(reply("Hi " + in.next().name)); + } + } +// end::backend-grpc-service[] + + private static HelloReply reply(String text) { + HelloReply r = new HelloReply(); + r.name = text; + return r; + } +// tag::backend-grpc-service[] +} +// end::backend-grpc-service[] diff --git a/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/GreeterCaller.java b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/GreeterCaller.java new file mode 100644 index 00000000000..eae487045d9 --- /dev/null +++ b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/GreeterCaller.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.backend.grpc; + +import com.codename1.backend.grpc.GrpcChannel; + +public class GreeterCaller { + public HelloReply call(String token, HelloRequest request) { + // tag::backend-grpc-client[] + GrpcChannel channel = GrpcChannel.forTarget("https://greeter.internal:8443") + .withMetadata("authorization", "Bearer " + token) + .withDeadlineMillis(2000); + HelloReply reply = channel.unary("/demo.Greeter/SayHello", + HelloRequestProtoCodec.INSTANCE, HelloReplyProtoCodec.INSTANCE, request); + // end::backend-grpc-client[] + return reply; + } +} diff --git a/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloReply.java b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloReply.java new file mode 100644 index 00000000000..9a3620ea02d --- /dev/null +++ b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloReply.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.backend.grpc; + +import com.codename1.annotations.grpc.ProtoField; +import com.codename1.annotations.grpc.ProtoMessage; + +@ProtoMessage +public class HelloReply { + @ProtoField(tag = 1) + public String name; +} diff --git a/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloReplyProtoCodec.java b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloReplyProtoCodec.java new file mode 100644 index 00000000000..b7c6f52597d --- /dev/null +++ b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloReplyProtoCodec.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.backend.grpc; + +import com.codename1.io.grpc.ProtoCodec; +import com.codename1.io.grpc.ProtoReader; +import com.codename1.io.grpc.ProtoWriter; +import java.io.IOException; + +/// Stands in for the codec the build generates for HelloReply. +public final class HelloReplyProtoCodec implements ProtoCodec { + public static final HelloReplyProtoCodec INSTANCE = new HelloReplyProtoCodec(); + + @Override + public void write(ProtoWriter w, HelloReply m) throws IOException { + if (m.name != null) { + w.writeString(1, m.name); + } + } + + @Override + public HelloReply read(ProtoReader r) throws IOException { + HelloReply m = new HelloReply(); + while (!r.isAtEnd()) { + int tag = r.readTag(); + if (tag >>> 3 == 1) { + m.name = r.readString(); + } else { + r.skipField(tag); + } + } + return m; + } +} diff --git a/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloRequest.java b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloRequest.java new file mode 100644 index 00000000000..25323b66d87 --- /dev/null +++ b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloRequest.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.backend.grpc; + +import com.codename1.annotations.grpc.ProtoField; +import com.codename1.annotations.grpc.ProtoMessage; + +@ProtoMessage +public class HelloRequest { + @ProtoField(tag = 1) + public String name; +} diff --git a/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloRequestProtoCodec.java b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloRequestProtoCodec.java new file mode 100644 index 00000000000..1e00e03a504 --- /dev/null +++ b/docs/demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/HelloRequestProtoCodec.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.backend.grpc; + +import com.codename1.io.grpc.ProtoCodec; +import com.codename1.io.grpc.ProtoReader; +import com.codename1.io.grpc.ProtoWriter; +import java.io.IOException; + +/// Stands in for the codec the build generates for HelloRequest. +public final class HelloRequestProtoCodec implements ProtoCodec { + public static final HelloRequestProtoCodec INSTANCE = new HelloRequestProtoCodec(); + + @Override + public void write(ProtoWriter w, HelloRequest m) throws IOException { + if (m.name != null) { + w.writeString(1, m.name); + } + } + + @Override + public HelloRequest read(ProtoReader r) throws IOException { + HelloRequest m = new HelloRequest(); + while (!r.isAtEnd()) { + int tag = r.readTag(); + if (tag >>> 3 == 1) { + m.name = r.readString(); + } else { + r.skipField(tag); + } + } + return m; + } +} diff --git a/docs/demos/common/src/main/snippets/developer-guide/backend-grpc.sh b/docs/demos/common/src/main/snippets/developer-guide/backend-grpc.sh new file mode 100644 index 00000000000..32d6f59652a --- /dev/null +++ b/docs/demos/common/src/main/snippets/developer-guide/backend-grpc.sh @@ -0,0 +1,6 @@ +// Generated from docs/developer-guide source blocks. Edit the guide snippets here, not inline. + +// tag::backend-grpc-generate[] +mvn cn1:generate-grpc -Dcn1.grpc.proto=src/main/proto/greeter.proto \ + -Dcn1.grpc.basePackage=com.example.greeter -Dcn1.grpc.target=backend +// end::backend-grpc-generate[] diff --git a/docs/developer-guide/Backend-Observability.asciidoc b/docs/developer-guide/Backend-Observability.asciidoc index 6144940622d..ddbc277873f 100644 --- a/docs/developer-guide/Backend-Observability.asciidoc +++ b/docs/developer-guide/Backend-Observability.asciidoc @@ -61,11 +61,11 @@ same way it configures everything else it runs: |=== | Variable | Property | Meaning -| `OTEL_EXPORTER_OTLP_ENDPOINT` | `cn1.otel.endpoint` | The collector's base URL; `/v1/traces` is appended. Defaults to `http://localhost:4318`. +| `OTEL_EXPORTER_OTLP_ENDPOINT` | `cn1.otel.endpoint` | The collector's base URL; `/v1/traces` is appended. Defaults to `http://localhost:4318`, or `http://localhost:4317` with gRPC, where only the scheme, host and port are used. | `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | `cn1.otel.traces.endpoint` | The full URL, used as it is. | `OTEL_EXPORTER_OTLP_HEADERS` | `cn1.otel.headers` | `name=value` pairs, comma separated, with each value URL-encoded. | `OTEL_EXPORTER_OTLP_TRACES_HEADERS` | `cn1.otel.traces.headers` | Headers for traces only, in place of the shared ones. -| `OTEL_EXPORTER_OTLP_PROTOCOL` | `cn1.otel.protocol` | `http/protobuf` or `http/json`. gRPC isn't supported. +| `OTEL_EXPORTER_OTLP_PROTOCOL` | `cn1.otel.protocol` | `http/protobuf`, `http/json`, or `grpc`: OTLP over gRPC, see <>. | `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` | `cn1.otel.traces.protocol` | The protocol for traces only. | `OTEL_SERVICE_NAME` | `cn1.otel.service.name` | Overrides the annotation's `serviceName`. | `OTEL_RESOURCE_ATTRIBUTES` | `cn1.otel.resource.attributes` | Extra resource attributes, `key=value` pairs. @@ -418,7 +418,7 @@ specification gives: | `OTEL_METRIC_EXPORT_INTERVAL` | `cn1.otel.metrics.intervalMillis` | How often to export, in milliseconds. A minute by default. | `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | `cn1.otel.metrics.endpoint` | The full URL. By default the tracing endpoint's base with `/v1/metrics` appended. | `OTEL_EXPORTER_OTLP_METRICS_HEADERS` | `cn1.otel.metrics.headers` | Headers for the metrics requests; by default the tracing ones. -| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | `cn1.otel.metrics.protocol` | `http/protobuf` or `http/json`; by default the tracing protocol. +| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | `cn1.otel.metrics.protocol` | `http/protobuf`, `http/json` or `grpc`; by default the tracing protocol. | | `cn1.otel.metrics.enabled` | `false` exports traces only. |=== diff --git a/docs/developer-guide/Backend-gRPC.asciidoc b/docs/developer-guide/Backend-gRPC.asciidoc new file mode 100644 index 00000000000..354218ebdda --- /dev/null +++ b/docs/developer-guide/Backend-gRPC.asciidoc @@ -0,0 +1,110 @@ +[[backend-grpc]] +== Backend gRPC + +A backend serves gRPC and calls gRPC services, with all four RPC shapes: unary, +server streaming, client streaming and bidirectional streaming. Calls travel +over the server's HTTP/2 listener, so a stock gRPC client in any language can +call a backend service. The same services also answer gRPC-Web over HTTP/1.1, +which is what the application's `@GrpcClient` and browsers send. + +=== Messages + +A message is a `@ProtoMessage` class whose fields carry `@ProtoField` tags, +the same classes an application uses. The build writes a codec for each one, +`ProtoCodec`, with a shared `INSTANCE`. Nothing is read by reflection +at run time. + +=== Serving a service + +A `@GrpcService` bean serves one service. Each `@Rpc` method serves one RPC, +and its signature says which shape the RPC has: + +[source,java,role=cn1-no-try] +---- +include::../demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/Greeter.java[tag=backend-grpc-service,indent=0] +---- + +* A method may also take a trailing `GrpcContext`. It reads the request + metadata and the deadline, says whether the client has gone, and adds + response headers and trailers. +* Throwing `GrpcException` ends the call with its status and message. Any other + exception ends it `UNKNOWN`. The exception is logged, and its message isn't + sent to the client. +* A streaming method returns when its stream is done: the call ends `OK` then. +* An RPC that no bean serves is answered `UNIMPLEMENTED`. A signature that + isn't one of the four shapes, and two methods serving the same RPC, are build + errors. + +The bean is an ordinary bean: it's injected, takes `@Transactional` and the +other aspects, and is wired to the server by the build. + +=== Generating from a `.proto` file + +`cn1:generate-grpc` writes the messages from a `.proto` file. With +`-Dcn1.grpc.target=backend`, it writes each service for a backend: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/backend-grpc.sh[tag=backend-grpc-generate,indent=0] +---- + +* `GreeterService`, an interface with one `@Rpc` method per RPC. A + `@GrpcService("demo.Greeter")` class that implements it serves the service. +* `GreeterClient`, a class that calls the service through a `GrpcChannel`. + +`stream` is accepted on either side of an RPC in this mode. + +=== Calling a service + +`GrpcChannel` calls a gRPC server: another backend, or any other +implementation. It's immutable, so one channel can be shared: + +[source,java,role=cn1-no-try] +---- +include::../demos/backend/src/main/java/com/codenameone/developerguide/backend/grpc/GreeterCaller.java[tag=backend-grpc-client,indent=0] +---- + +* `serverStreaming` answers a `GrpcChannel.Call`, an `Iterator` of the + responses as they arrive. +* `clientStreaming` sends every message of an `Iterator` and answers the one + response. +* `bidiStreaming` answers an open `Call`: `send` and `complete` write the + request stream, and the iterator reads responses meanwhile. +* A call that fails throws `GrpcException`. A server that can't be reached is + `UNAVAILABLE`, and a call past its deadline is `DEADLINE_EXCEEDED`. + +`http://` targets are spoken as HTTP/2 without TLS (h2c), and `https://` +targets negotiate HTTP/2 through ALPN. + +=== Protocol details + +* Messages may be compressed with gzip in either direction. `withGzip(true)` + compresses a channel's requests. +* `-bin` metadata is base64 encoded on the wire and read as bytes by + `GrpcContext.getBinary`. +* `grpc-timeout` sets the call's deadline. A handler that's still running at + the deadline isn't interrupted: it should check + `GrpcContext.isDeadlineExceeded` between units of work. +* Messages larger than 4 MiB are refused with `RESOURCE_EXHAUSTED`, in + either direction; `GrpcServer.setMaxMessageSize` and + `GrpcChannel.withMaxMessageSize` change it. +* The calls of one HTTP/2 connection are served one at a time, in the order + they arrive. Separate connections are served in parallel. + Clients such as grpc-java put every call of a channel on one connection, so + a long-lived streaming call (a watch or a subscription) holds back every + call queued behind it. Give such calls a channel of their own. +* Over gRPC-Web on HTTP/1.1, the response headers are sent before the handler + runs, so headers a handler adds through `GrpcContext` aren't sent; trailers + are. `GrpcContext.isCancelled` is answered only over HTTP/2; over gRPC-Web a + departed client shows up as a failed write. +* A server-streaming call holds its connection until the stream is read to the + end or the call is closed: a caller that stops early calls `close()`. + +=== OpenTelemetry over gRPC + +`cn1.otel.protocol=grpc` exports traces and metrics with OTLP over gRPC, to the +collector's `TraceService/Export` and `MetricsService/Export`. The endpoint +defaults to `http://localhost:4317`, the collector's gRPC port, and +`cn1.otel.headers` travel as call metadata. `UNAVAILABLE`, +`RESOURCE_EXHAUSTED` and `DEADLINE_EXCEEDED` are retried as the HTTP exporter +retries a 503; see <>. diff --git a/docs/developer-guide/appendix_goal_generate_grpc.adoc b/docs/developer-guide/appendix_goal_generate_grpc.adoc index 1b8c3c12f4e..1ad4b9a5817 100644 --- a/docs/developer-guide/appendix_goal_generate_grpc.adoc +++ b/docs/developer-guide/appendix_goal_generate_grpc.adoc @@ -128,6 +128,9 @@ invokes the supplied `OnComplete>`. * Unary RPCs (single request, single response). Streaming RPCs (`stream` keyword on request or response) are rejected at generation time -- gRPC-Web client streaming requires HTTP/2. +With `-Dcn1.grpc.target=backend` all four shapes are accepted, and +each service is written as a backend service interface and a +`GrpcChannel` client instead; see <>. * proto3 syntax. proto2 `required` is rejected; `optional` is accepted but treated as a nullable field. * Scalar types: `int32`, `int64`, `uint32`, `uint64`, `sint32`, @@ -145,7 +148,8 @@ both packed and unpacked forms. message -- the mutual-exclusion guarantee is lost but round-trips work. Use application code to enforce the invariant if needed. * Not yet supported: `map`, well-known types (Timestamp, -Empty, etc.), file `import`, streaming RPCs. These produce a clear +Empty, etc.), file `import`, and streaming RPCs for the application +client. These produce a clear error from the parser pointing at the offending line. * Authentication: a bearer token is exposed uniformly as a `@Header("Authorization") String bearerToken` parameter on every diff --git a/docs/developer-guide/developer-guide.asciidoc b/docs/developer-guide/developer-guide.asciidoc index 5bc5918306f..07529be6771 100644 --- a/docs/developer-guide/developer-guide.asciidoc +++ b/docs/developer-guide/developer-guide.asciidoc @@ -165,6 +165,8 @@ include::Backend-Observability.asciidoc[] include::Backend-GraphQL.asciidoc[] +include::Backend-gRPC.asciidoc[] + include::Backend-MCP.asciidoc[] include::Backend-Operations.asciidoc[] diff --git a/maven/backend/spotbugs-exclude.xml b/maven/backend/spotbugs-exclude.xml index 42a5acf1fe4..b03934a0eee 100644 --- a/maven/backend/spotbugs-exclude.xml +++ b/maven/backend/spotbugs-exclude.xml @@ -24,6 +24,13 @@ CLAUDE.md. --> + + + + + + diff --git a/maven/backend/src/test/java/com/codename1/backend/GrpcEndToEndTest.java b/maven/backend/src/test/java/com/codename1/backend/GrpcEndToEndTest.java new file mode 100644 index 00000000000..ed64c1b1794 --- /dev/null +++ b/maven/backend/src/test/java/com/codename1/backend/GrpcEndToEndTest.java @@ -0,0 +1,475 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend; + +import com.codename1.backend.grpc.GrpcChannel; +import com.codename1.backend.grpc.GrpcContext; +import com.codename1.backend.grpc.GrpcException; +import com.codename1.backend.grpc.GrpcMethod; +import com.codename1.backend.grpc.GrpcServer; +import com.codename1.backend.grpc.GrpcStatus; +import com.codename1.backend.grpc.StreamObserver; +import com.codename1.io.grpc.ProtoCodec; +import com.codename1.io.grpc.ProtoReader; +import com.codename1.io.grpc.ProtoWriter; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.ServerSocket; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/// gRPC end to end on the JavaSE runtime: the HTTP server's HTTP/2 path and +/// gRPC-Web path against the pure-Java client, every RPC shape and the error +/// paths a real client depends on. +class GrpcEndToEndTest { + /// A message with one string field, number 1. + static final ProtoCodec TEXT = new ProtoCodec() { + @Override + public void write(ProtoWriter w, String value) throws IOException { + w.writeString(1, value); + } + + @Override + public String read(ProtoReader r) throws IOException { + String out = ""; + while (!r.isAtEnd()) { + int tag = r.readTag(); + if (tag >>> 3 == 1) { + out = r.readString(); + } else { + r.skipField(tag); + } + } + return out; + } + }; + + private static final String SVC = "test.Echo"; + + /// The handler a Backend gives the server, reduced to what this needs. + static final class Hosting implements HttpServer.Handler, HttpServer.GrpcHosting { + final GrpcServer grpc; + + Hosting(GrpcServer grpc) { + this.grpc = grpc; + } + + @Override + public HttpServer.Response handle(HttpServer.Request request) throws Exception { + HttpServer.Response r = grpc.handle(request); + return r != null ? r : HttpServer.Response.text(404, "no"); + } + + @Override + public GrpcServer grpcServer() { + return grpc; + } + } + + private HttpServer server; + private GrpcChannel channel; + + @BeforeEach + void start() throws Exception { + GrpcServer grpc = new GrpcServer() + .add(GrpcMethod.unary(SVC, "Say", TEXT, TEXT, (req, ctx) -> { + String s = (String) req; + if (s.startsWith("fail:")) { + throw new GrpcException(GrpcStatus.INVALID_ARGUMENT, s.substring(5)); + } + if (s.equals("boom")) { + throw new IllegalStateException("secret internals"); + } + if (s.equals("slow")) { + Thread.sleep(400); + } + String who = ctx.get("x-who"); + ctx.addTrailer("x-done", "yes"); + return "hello " + s + (who == null ? "" : " from " + who); + })) + .add(GrpcMethod.serverStreaming(SVC, "Count", TEXT, TEXT, (req, out, ctx) -> { + int n = Integer.parseInt((String) req); + for (int i = 0; i < n; i++) { + out.onNext("n" + i); + } + if (n == 2) { + out.onError(new GrpcException(GrpcStatus.ABORTED, "stopped at two")); + return; + } + out.onCompleted(); + })) + .add(GrpcMethod.clientStreaming(SVC, "Join", TEXT, TEXT, (reqs, ctx) -> { + StringBuilder b = new StringBuilder(); + while (reqs.hasNext()) { + b.append(reqs.next()); + } + return b.toString(); + })) + .add(GrpcMethod.bidiStreaming(SVC, "Chat", TEXT, TEXT, (reqs, out, ctx) -> { + while (reqs.hasNext()) { + out.onNext("re:" + reqs.next()); + } + })); + server = HttpServer.start("127.0.0.1", 0, 16, 2, new Hosting(grpc)); + channel = GrpcChannel.forTarget("http://127.0.0.1:" + server.getPort()); + } + + @AfterEach + void stop() { + server.stop(1000); + } + + @Test + void aPeerThatStallsFailsTheCallAtItsDeadline() throws Exception { + // Accepts the connection and never answers: the call must end at its + // deadline instead of blocking on the socket forever. + ServerSocket silent = new ServerSocket(0); + try { + GrpcChannel stalled = GrpcChannel.forTarget("http://127.0.0.1:" + silent.getLocalPort()) + .withDeadlineMillis(300); + long start = System.nanoTime(); + GrpcException e = assertThrows(GrpcException.class, + () -> stalled.unary("/test.Echo/Unary", new byte[] {1})); + assertEquals(GrpcStatus.DEADLINE_EXCEEDED, e.getStatus()); + assertTrue(System.nanoTime() - start < 10000000000L); + } finally { + silent.close(); + } + } + + @Test + void grpcWebIsNotTakenForNativeGrpc() { + assertTrue(GrpcServer.isGrpc("application/grpc")); + assertTrue(GrpcServer.isGrpc("application/grpc+proto")); + assertTrue(GrpcServer.isGrpc("application/grpc;charset=utf-8")); + assertFalse(GrpcServer.isGrpc("application/grpc-web+proto")); + assertFalse(GrpcServer.isGrpc("application/grpcfoo")); + } + + @Test + void unary() { + assertEquals("hello you", channel.unary("/test.Echo/Say", TEXT, TEXT, "you")); + assertEquals("hello me from tester", channel.withMetadata("x-who", "tester") + .unary("/test.Echo/Say", TEXT, TEXT, "me")); + } + + @Test + void manyCallsInARow() { + for (int i = 0; i < 50; i++) { + assertEquals("hello " + i, channel.unary("/test.Echo/Say", TEXT, TEXT, "" + i)); + } + } + + @Test + void largeMessagesBothWays() { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < 300000; i++) { + b.append((char) ('a' + i % 26)); + } + String big = b.toString(); + assertEquals("hello " + big, channel.unary("/test.Echo/Say", TEXT, TEXT, big)); + assertEquals("hello " + big, channel.withGzip(true).unary("/test.Echo/Say", TEXT, TEXT, big)); + } + + @Test + void statusesAndTrailers() { + GrpcException e = assertThrows(GrpcException.class, + () -> channel.unary("/test.Echo/Say", TEXT, TEXT, "fail:bad input %")); + assertEquals(GrpcStatus.INVALID_ARGUMENT, e.getStatus()); + assertEquals("bad input %", e.getMessage()); + e = assertThrows(GrpcException.class, () -> channel.unary("/test.Echo/Say", TEXT, TEXT, "boom")); + assertEquals(GrpcStatus.UNKNOWN, e.getStatus()); + assertFalse(String.valueOf(e.getMessage()).contains("secret")); + e = assertThrows(GrpcException.class, () -> channel.unary("/test.Echo/Nope", TEXT, TEXT, "x")); + assertEquals(GrpcStatus.UNIMPLEMENTED, e.getStatus()); + } + + @Test + void deadline() { + GrpcException e = assertThrows(GrpcException.class, () -> channel.withDeadlineMillis(100) + .unary("/test.Echo/Say", TEXT, TEXT, "slow")); + assertEquals(GrpcStatus.DEADLINE_EXCEEDED, e.getStatus()); + } + + @Test + void serverStreaming() { + GrpcChannel.Call call = channel.serverStreaming("/test.Echo/Count", TEXT, TEXT, "4"); + List got = new ArrayList(); + while (call.hasNext()) { + got.add(call.next()); + } + call.close(); + assertEquals(Arrays.asList("n0", "n1", "n2", "n3"), got); + call = channel.serverStreaming("/test.Echo/Count", TEXT, TEXT, "2"); + assertEquals("n0", call.next()); + assertEquals("n1", call.next()); + GrpcChannel.Call failing = call; + GrpcException e = assertThrows(GrpcException.class, failing::hasNext); + assertEquals(GrpcStatus.ABORTED, e.getStatus()); + call.close(); + } + + @Test + void clientStreaming() { + Iterator parts = Arrays.asList("a", "b", "c").iterator(); + assertEquals("abc", channel.clientStreaming("/test.Echo/Join", TEXT, TEXT, parts)); + assertEquals("", channel.clientStreaming("/test.Echo/Join", TEXT, TEXT, + new ArrayList().iterator())); + } + + @Test + void bidi() { + GrpcChannel.Call call = channel.bidiStreaming("/test.Echo/Chat", TEXT, TEXT); + try { + call.send("one"); + call.send("two"); + call.complete(); + assertTrue(call.hasNext()); + assertEquals("re:one", call.next()); + assertEquals("re:two", call.next()); + assertFalse(call.hasNext()); + assertEquals("0", call.getTrailers().get("grpc-status")); + } finally { + call.close(); + } + } + + @Test + void grpcWebOverHttp1() throws Exception { + URL url = new URL("http://127.0.0.1:" + server.getPort() + "/test.Echo/Say"); + HttpURLConnection c = (HttpURLConnection) url.openConnection(); + c.setDoOutput(true); + c.setRequestMethod("POST"); + c.setRequestProperty("content-type", "application/grpc-web+proto"); + ByteArrayOutputStream msg = new ByteArrayOutputStream(); + TEXT.write(new ProtoWriter(msg), "web"); + byte[] body = msg.toByteArray(); + try (OutputStream o = c.getOutputStream()) { + o.write(new byte[] {0, 0, 0, 0, (byte) body.length}); + o.write(body); + } + assertEquals(200, c.getResponseCode()); + byte[] all; + try (InputStream in = c.getInputStream()) { + ByteArrayOutputStream b = new ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int n; + while ((n = in.read(buf)) > 0) { + b.write(buf, 0, n); + } + all = b.toByteArray(); + } + assertEquals(0, all[0]); + int len = ((all[1] & 0xff) << 24) | ((all[2] & 0xff) << 16) | ((all[3] & 0xff) << 8) | (all[4] & 0xff); + assertEquals("hello web", TEXT.read(new ProtoReader(Arrays.copyOfRange(all, 5, 5 + len)))); + assertEquals((byte) 0x80, all[5 + len]); + String trailer = new String(all, 10 + len, all.length - 10 - len, "UTF-8"); + assertTrue(trailer.contains("grpc-status:0"), trailer); + assertTrue(trailer.contains("x-done:yes"), trailer); + } + + // ---------------------------------------------------------------- interop + // Against gRPC C-core (grpcio), with vm/backend/grpc-interop/interop.py. + // Set CN1_GRPC_INTEROP_PYTHON to a python that has grpcio installed. + + private static String interopPython() { + String py = System.getenv("CN1_GRPC_INTEROP_PYTHON"); + assumeTrue(py != null && py.length() > 0, "CN1_GRPC_INTEROP_PYTHON is not set"); + return py; + } + + private static File interopScript() { + File f = new File("../../vm/backend/grpc-interop/interop.py").getAbsoluteFile(); + assertTrue(f.isFile(), f.toString()); + return f; + } + + private static String drain(Process p) throws IOException { + StringBuilder b = new StringBuilder(); + try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8"))) { + String line; + while ((line = r.readLine()) != null) { + b.append(line).append('\n'); + } + } + return b.toString(); + } + + @Test + void grpcCoreClientAgainstThisServer() throws Exception { + String py = interopPython(); + Process p = new ProcessBuilder(py, interopScript().getPath(), "client", + "127.0.0.1:" + server.getPort()).redirectErrorStream(true).start(); + String out = drain(p); + assertEquals(0, p.waitFor(), out); + assertTrue(out.contains("INTEROP OK"), out); + } + + @Test + void thisClientAgainstGrpcCoreServer() throws Exception { + String py = interopPython(); + int port; + try (ServerSocket probe = new ServerSocket(0)) { + port = probe.getLocalPort(); + } + Process p = new ProcessBuilder(py, interopScript().getPath(), "server", "" + port) + .redirectErrorStream(true).start(); + try { + BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8")); + assertEquals("READY", r.readLine()); + GrpcChannel c = GrpcChannel.forTarget("http://127.0.0.1:" + port); + assertEquals("hello py", c.unary("/test.Echo/Say", TEXT, TEXT, "py")); + assertEquals("hello m from j", c.withMetadata("x-who", "j") + .unary("/test.Echo/Say", TEXT, TEXT, "m")); + StringBuilder big = new StringBuilder(); + for (int i = 0; i < 300000; i++) { + big.append('y'); + } + assertEquals("hello " + big, c.withGzip(true).unary("/test.Echo/Say", TEXT, TEXT, + big.toString())); + GrpcException e = assertThrows(GrpcException.class, + () -> c.unary("/test.Echo/Say", TEXT, TEXT, "fail:bad input %")); + assertEquals(GrpcStatus.INVALID_ARGUMENT, e.getStatus()); + assertEquals("bad input %", e.getMessage()); + e = assertThrows(GrpcException.class, () -> c.unary("/test.Echo/Nope", TEXT, TEXT, "x")); + assertEquals(GrpcStatus.UNIMPLEMENTED, e.getStatus()); + GrpcChannel.Call s = c.serverStreaming("/test.Echo/Count", TEXT, TEXT, "3"); + List got = new ArrayList(); + while (s.hasNext()) { + got.add(s.next()); + } + s.close(); + assertEquals(Arrays.asList("n0", "n1", "n2"), got); + GrpcChannel.Call two = c.serverStreaming("/test.Echo/Count", TEXT, TEXT, "2"); + two.next(); + two.next(); + e = assertThrows(GrpcException.class, two::hasNext); + assertEquals(GrpcStatus.ABORTED, e.getStatus()); + two.close(); + assertEquals("abc", c.clientStreaming("/test.Echo/Join", TEXT, TEXT, + Arrays.asList("a", "b", "c").iterator())); + GrpcChannel.Call chat = c.bidiStreaming("/test.Echo/Chat", TEXT, TEXT); + chat.send("one"); + assertEquals("re:one", chat.next()); + chat.send("two"); + assertEquals("re:two", chat.next()); + chat.complete(); + assertFalse(chat.hasNext()); + chat.close(); + } finally { + p.destroyForcibly(); + } + } + + /// Counts the top-level field-1 entries of an OTLP export request + /// (resource_spans or resource_metrics) and answers an empty response. + static ProtoCodec countingCodec() { + return new ProtoCodec() { + @Override + public void write(ProtoWriter w, Integer value) { + } + + @Override + public Integer read(ProtoReader r) throws IOException { + int n = 0; + while (!r.isAtEnd()) { + int tag = r.readTag(); + if (tag >>> 3 == 1) { + r.readBytes(); + n++; + } else { + r.skipField(tag); + } + } + return Integer.valueOf(n); + } + }; + } + + @Test + void otlpExportsTracesOverGrpc() throws Exception { + final java.util.concurrent.atomic.AtomicInteger spans = + new java.util.concurrent.atomic.AtomicInteger(); + final java.util.concurrent.atomic.AtomicReference auth = + new java.util.concurrent.atomic.AtomicReference(); + ProtoCodec c = countingCodec(); + GrpcServer collector = new GrpcServer() + .add(GrpcMethod.unary("opentelemetry.proto.collector.trace.v1.TraceService", + "Export", c, c, (req, ctx) -> { + auth.set(ctx.get("authorization")); + spans.addAndGet(((Integer) req).intValue()); + return Integer.valueOf(0); + })) + .add(GrpcMethod.unary("opentelemetry.proto.collector.metrics.v1.MetricsService", + "Export", c, c, (req, ctx) -> Integer.valueOf(0))); + HttpServer collectorServer = HttpServer.start("127.0.0.1", 0, 16, 2, new Hosting(collector)); + int port; + try (ServerSocket ss = new ServerSocket(0)) { + port = ss.getLocalPort(); + } + java.util.Properties settings = new java.util.Properties(); + settings.setProperty(Config.SERVER_PORT, String.valueOf(port)); + settings.setProperty("cn1.otel.protocol", "grpc"); + settings.setProperty("cn1.otel.endpoint", "http://127.0.0.1:" + collectorServer.getPort()); + settings.setProperty("cn1.otel.headers", "Authorization=Bearer t0ken"); + settings.setProperty("cn1.otel.export.delayMillis", "100"); + Backend backend = Backend.builder(Config.of(settings, "test")).quiet() + .tracing(new com.codename1.backend.otel.OtlpTracer()) + .handler(request -> HttpServer.Response.text(200, "ok")) + .start(); + try { + HttpURLConnection conn = (HttpURLConnection) new URL("http://127.0.0.1:" + port + "/x") + .openConnection(); + assertEquals(200, conn.getResponseCode()); + long deadline = System.currentTimeMillis() + 15000; + while (spans.get() == 0 && System.currentTimeMillis() < deadline) { + Thread.sleep(50); + } + assertTrue(spans.get() > 0, "no span reached the gRPC collector"); + assertEquals("Bearer t0ken", auth.get()); + } finally { + backend.stop(); + collectorServer.stop(); + } + } +} diff --git a/maven/backend/src/test/java/com/codename1/backend/grpc/GrpcProtocolTest.java b/maven/backend/src/test/java/com/codename1/backend/grpc/GrpcProtocolTest.java new file mode 100644 index 00000000000..f6c903ee089 --- /dev/null +++ b/maven/backend/src/test/java/com/codename1/backend/grpc/GrpcProtocolTest.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// The gRPC framing and header encodings, driven byte by byte. +class GrpcProtocolTest { + + private static byte[] bytes(int n, int seed) { + byte[] b = new byte[n]; + for (int i = 0; i < n; i++) { + b[i] = (byte) (i * 31 + seed); + } + return b; + } + + @Test + void framesSplitAtEveryByteBoundaryReassemble() { + byte[] a = bytes(300, 1); + byte[] b = new byte[0]; + byte[] c = bytes(70000, 7); + byte[] wire = concat(GrpcFrames.frame(a), GrpcFrames.frame(b), GrpcFrames.frame(c, true)); + for (int chunk = 1; chunk <= 13; chunk++) { + GrpcFrames.Decoder d = new GrpcFrames.Decoder(GrpcFrames.DEFAULT_MAX_MESSAGE, true); + List got = new ArrayList(); + for (int pos = 0; pos < wire.length; pos += chunk) { + got.addAll(d.feed(wire, pos, Math.min(chunk, wire.length - pos))); + } + assertEquals(3, got.size(), "chunk " + chunk); + assertArrayEquals(a, got.get(0)); + assertArrayEquals(b, got.get(1)); + assertArrayEquals(c, got.get(2)); + assertTrue(d.isIdle()); + } + } + + @Test + void wholeStreamInOneFeed() { + byte[] wire = concat(GrpcFrames.frame(bytes(5, 2)), GrpcFrames.frame(bytes(9, 3))); + assertEquals(2, new GrpcFrames.Decoder(100, false).feed(wire, 0, wire.length).size()); + } + + @Test + void partialMessageIsNotIdle() { + byte[] wire = GrpcFrames.frame(bytes(10, 0)); + GrpcFrames.Decoder d = new GrpcFrames.Decoder(100, false); + assertTrue(d.feed(wire, 0, 7).isEmpty()); + assertFalse(d.isIdle()); + } + + @Test + void oversizedLengthRefusedBeforeAllocating() { + byte[] prefix = {0, (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff}; + GrpcException e = assertThrows(GrpcException.class, + () -> new GrpcFrames.Decoder(1024, false).feed(prefix, 0, 5)); + assertEquals(GrpcStatus.RESOURCE_EXHAUSTED, e.getStatus()); + } + + @Test + void compressedWithoutNegotiationIsInternal() { + byte[] wire = GrpcFrames.frame(bytes(10, 0), true); + GrpcException e = assertThrows(GrpcException.class, + () -> new GrpcFrames.Decoder(1024, false).feed(wire, 0, wire.length)); + assertEquals(GrpcStatus.INTERNAL, e.getStatus()); + } + + @Test + void reservedFlagIsInternal() { + byte[] wire = {2, 0, 0, 0, 0}; + assertEquals(GrpcStatus.INTERNAL, assertThrows(GrpcException.class, + () -> new GrpcFrames.Decoder(1024, true).feed(wire, 0, 5)).getStatus()); + } + + @Test + void gzipBombBoundedAfterInflation() { + byte[] wire = GrpcFrames.frame(new byte[100000], true); + assertTrue(wire.length < 2000); + assertEquals(GrpcStatus.RESOURCE_EXHAUSTED, assertThrows(GrpcException.class, + () -> new GrpcFrames.Decoder(50000, true).feed(wire, 0, wire.length)).getStatus()); + } + + @Test + void timeouts() { + assertEquals(1500000000L, GrpcMetadata.parseTimeoutNanos("1500m")); + assertEquals(60000000000L, GrpcMetadata.parseTimeoutNanos("1M")); + assertEquals(3600000000000L, GrpcMetadata.parseTimeoutNanos("1H")); + assertEquals(2000L, GrpcMetadata.parseTimeoutNanos("2u")); + assertEquals(7L, GrpcMetadata.parseTimeoutNanos("7n")); + assertEquals(10000000000L, GrpcMetadata.parseTimeoutNanos("10S")); + assertEquals(-1, GrpcMetadata.parseTimeoutNanos("123456789S")); + assertEquals(-1, GrpcMetadata.parseTimeoutNanos("10s")); + assertEquals(-1, GrpcMetadata.parseTimeoutNanos("S")); + assertEquals(-1, GrpcMetadata.parseTimeoutNanos(null)); + assertEquals("250m", GrpcMetadata.formatTimeoutMillis(250)); + assertEquals("1m", GrpcMetadata.formatTimeoutMillis(0)); + assertEquals("100000S", GrpcMetadata.formatTimeoutMillis(100000000L)); + String max = GrpcMetadata.formatTimeoutMillis(Long.MAX_VALUE / 2); + assertTrue(GrpcMetadata.parseTimeoutNanos(max) > 0, max); + } + + @Test + void statusMessageRoundTrip() { + String m = "bad 100% \u00e9t\u00e9\n\u4e2d"; + String enc = GrpcMetadata.encodeMessage(m); + for (int i = 0; i < enc.length(); i++) { + char c = enc.charAt(i); + assertTrue(c >= 0x20 && c <= 0x7e, enc); + } + assertEquals(m, GrpcMetadata.decodeMessage(enc)); + assertEquals("50%", GrpcMetadata.decodeMessage("50%")); + assertEquals("a%zzb", GrpcMetadata.decodeMessage("a%zzb")); + assertEquals("", GrpcMetadata.encodeMessage(null)); + } + + @Test + void binaryMetadata() { + assertTrue(GrpcMetadata.isBinary("trace-BIN")); + assertFalse(GrpcMetadata.isBinary("-bin")); + assertFalse(GrpcMetadata.isBinary("binary")); + for (int n = 0; n < 8; n++) { + byte[] b = bytes(n, n); + String enc = GrpcMetadata.encodeBinary(b); + assertFalse(enc.endsWith("=")); + assertArrayEquals(b, GrpcMetadata.decodeBinary(enc)); + assertArrayEquals(b, GrpcMetadata.decodeBinary(java.util.Base64.getEncoder().encodeToString(b))); + } + assertNull(GrpcMetadata.decodeBinary("abcde")); + } + + @Test + void statusCodes() { + assertEquals("UNAVAILABLE", GrpcStatus.name(14)); + assertEquals("CODE_99", GrpcStatus.name(99)); + assertEquals(GrpcStatus.UNIMPLEMENTED, GrpcStatus.fromHttpStatus(404)); + assertEquals(GrpcStatus.UNKNOWN, GrpcStatus.parse("1x")); + assertEquals(5, GrpcStatus.parse("5")); + } + + private static byte[] concat(byte[]... parts) { + int n = 0; + for (byte[] p : parts) { + n += p.length; + } + byte[] out = new byte[n]; + int pos = 0; + for (byte[] p : parts) { + System.arraycopy(p, 0, out, pos, p.length); + pos += p.length; + } + return out; + } +} diff --git a/maven/backend/src/test/java/com/codename1/backend/h2/HpackTest.java b/maven/backend/src/test/java/com/codename1/backend/h2/HpackTest.java new file mode 100644 index 00000000000..a3154354b78 --- /dev/null +++ b/maven/backend/src/test/java/com/codename1/backend/h2/HpackTest.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.h2; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/// HPACK against the RFC 7541 Appendix C examples, plus the refusals the RFC +/// requires and a randomized encoder/decoder round trip. +class HpackTest { + + private static byte[] hex(String s) { + String h = s.replace(" ", ""); + byte[] out = new byte[h.length() / 2]; + for (int i = 0; i < out.length; i++) { + out[i] = (byte) Integer.parseInt(h.substring(2 * i, 2 * i + 2), 16); + } + return out; + } + + private static List decode(Hpack.Decoder d, String hex) throws Exception { + byte[] b = hex(hex); + return d.decode(b, 0, b.length); + } + + @Test + void rfcC4RequestsWithHuffman() throws Exception { + Hpack.Decoder d = new Hpack.Decoder(4096, 1 << 20); + assertEquals(Arrays.asList(":method", "GET", ":scheme", "http", ":path", "/", + ":authority", "www.example.com"), + decode(d, "8286 8441 8cf1 e3c2 e5f2 3a6b a0ab 90f4 ff")); + assertEquals(57, d.tableSize()); + assertEquals(Arrays.asList(":method", "GET", ":scheme", "http", ":path", "/", + ":authority", "www.example.com", "cache-control", "no-cache"), + decode(d, "8286 84be 5886 a8eb 1064 9cbf")); + assertEquals(110, d.tableSize()); + assertEquals(Arrays.asList(":method", "GET", ":scheme", "https", ":path", "/index.html", + ":authority", "www.example.com", "custom-key", "custom-value"), + decode(d, "8287 85bf 4088 25a8 49e9 5ba9 7d7f 8925 a849 e95b b8e8 b4bf")); + assertEquals(164, d.tableSize()); + } + + @Test + void rfcC2LiteralForms() throws Exception { + // C.2.1 literal with indexing, C.2.2 without, C.2.3 never indexed, C.2.4 indexed. + Hpack.Decoder d = new Hpack.Decoder(4096, 1 << 20); + assertEquals(Arrays.asList("custom-key", "custom-header"), + decode(d, "400a 6375 7374 6f6d 2d6b 6579 0d63 7573 746f 6d2d 6865 6164 6572")); + assertEquals(55, d.tableSize()); + Hpack.Decoder d2 = new Hpack.Decoder(4096, 1 << 20); + assertEquals(Arrays.asList(":path", "/sample/path"), + decode(d2, "040c 2f73 616d 706c 652f 7061 7468")); + assertEquals(0, d2.tableSize()); + assertEquals(Arrays.asList("password", "secret"), + decode(d2, "1008 7061 7373 776f 7264 0673 6563 7265 74")); + assertEquals(Arrays.asList(":method", "GET"), decode(d2, "82")); + } + + @Test + void evictionUnderSmallTable() throws Exception { + Hpack.Decoder d = new Hpack.Decoder(60, 1 << 20); + decode(d, "400a 6375 7374 6f6d 2d6b 6579 0d63 7573 746f 6d2d 6865 6164 6572"); + assertEquals(55, d.tableSize()); + // Same entry again evicts the first: still 55. + decode(d, "400a 6375 7374 6f6d 2d6b 6579 0d63 7573 746f 6d2d 6865 6164 6572"); + assertEquals(55, d.tableSize()); + assertEquals(Arrays.asList("custom-key", "custom-header"), decode(d, "be")); + assertThrows(Hpack.CompressionException.class, () -> decode(d, "bf")); + } + + @Test + void refusals() { + Hpack.Decoder d = new Hpack.Decoder(4096, 1 << 20); + assertThrows(Hpack.CompressionException.class, () -> decode(d, "80")); + assertThrows(Hpack.CompressionException.class, () -> decode(d, "ff ff ff ff ff 0f")); + assertThrows(Hpack.CompressionException.class, () -> decode(d, "3fe2 1f")); + assertThrows(Hpack.CompressionException.class, () -> decode(d, "82 20")); + // Huffman string "a" padded with zeros instead of ones. + assertThrows(Hpack.CompressionException.class, () -> decode(d, "0001 0081 00")); + // Eight bits of padding. + assertThrows(Hpack.CompressionException.class, () -> decode(d, "0001 6182 1fff")); + // EOS inside a string. + assertThrows(Hpack.CompressionException.class, () -> decode(d, "0001 6184 ffff ffff")); + assertThrows(Hpack.CompressionException.class, () -> decode(d, "0001 6105 61")); + Hpack.Decoder small = new Hpack.Decoder(4096, 40); + assertThrows(Hpack.HeaderListTooLargeException.class, + () -> decode(small, "8286")); + } + + @Test + void randomRoundTrip() throws Exception { + Random r = new Random(5); + Hpack.Encoder e = new Hpack.Encoder(); + Hpack.Decoder d = new Hpack.Decoder(4096, 1 << 24); + for (int iter = 0; iter < 500; iter++) { + List h = new ArrayList(); + int n = r.nextInt(8); + for (int i = 0; i < n; i++) { + String[] s = Hpack.STATIC_TABLE[r.nextInt(Hpack.STATIC_TABLE.length)]; + h.add(r.nextBoolean() ? s[0] : "x-" + iter + "-" + i); + StringBuilder v = new StringBuilder(); + int len = r.nextInt(40); + for (int k = 0; k < len; k++) { + v.append((char) r.nextInt(256)); + } + h.add(r.nextInt(4) == 0 ? s[1] : v.toString()); + } + if (iter % 50 == 0) { + e.peerTableSizeChanged(); + } + byte[] block = e.encode(h); + assertEquals(h, d.decode(block, 0, block.length)); + } + } +} diff --git a/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendBeans.java b/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendBeans.java index 8adee67f4d5..7f4e7dae4a3 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendBeans.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendBeans.java @@ -149,7 +149,7 @@ final class BackendBeans { /// Every annotation this pass reads, for the processor's declared interest. static final Set DESCRIPTORS = Collections.unmodifiableSet( - new LinkedHashSet(java.util.Arrays.asList(COMPONENT, + new LinkedHashSet(java.util.Arrays.asList(COMPONENT, BackendGrpc.GRPC_SERVICE, CONFIGURATION, BEAN, AUTOWIRED, VALUE, CONFIG_PROPERTIES, SCOPE, PROFILE, ON_PROPERTY, ON_EXPRESSION, ON_MISSING, POST_CONSTRUCT, PRE_DESTROY, TRANSACTIONAL, ASYNC, SCHEDULED, @@ -162,7 +162,7 @@ final class BackendBeans { BackendExceptionHandlers.REST_CONTROLLER_ADVICE))); private static final String[] STEREOTYPES = {COMPONENT, CONFIGURATION, - REST_CONTROLLER, MVC_CONTROLLER, WEBSOCKET_MAPPING, + REST_CONTROLLER, MVC_CONTROLLER, WEBSOCKET_MAPPING, BackendGrpc.GRPC_SERVICE, BackendExceptionHandlers.CONTROLLER_ADVICE, BackendExceptionHandlers.REST_CONTROLLER_ADVICE}; @@ -404,6 +404,9 @@ static final class Bean { /// Its GraphQL resolvers, and the adapter class registering them. final List graphql = new ArrayList(); String graphqlAdapter; + /// Its gRPC methods, and the adapter class registering them. + final List grpc = new ArrayList(); + String grpcAdapter; Managed managed; /// Request, session and lazy beans: the number the build gives each. int slot = -1; @@ -752,6 +755,7 @@ private void applyMocks() { /// The adapter class names the wiring registers, as the main build named them. private void nameAdapters() { BackendGraphQL.name(this); + BackendGrpc.name(this); for (Bean b : beans) { String pkg = RestClientAnnotationProcessor.packageOf(b.type.replace('/', '.')); for (int i = 0; i < b.tools.size(); i++) { @@ -897,6 +901,16 @@ static boolean isSecurityChain(Bean b) { /// has none and serves no GraphQL. String graphQLSchema; + /// Whether any bean serves gRPC methods. + boolean hasGrpc() { + for (Bean b : beans) { + if (!b.grpc.isEmpty()) { + return true; + } + } + return false; + } + boolean hasGraphQL() { return graphQLSchema != null; } @@ -1058,6 +1072,7 @@ private Bean classBean(AnnotatedClass cls) { collectJobs(bean); collectTools(bean); BackendGraphQL.collect(this, bean); + BackendGrpc.collect(this, bean); collectManaged(bean); return bean; } @@ -1221,7 +1236,7 @@ private static String explicitName(AnnotatedClass cls) { for (String s : STEREOTYPES) { AnnotationValues v = cls.getClassAnnotation(s); if (v != null && v.getString("value") != null && !REST_CONTROLLER.equals(s) - && !WEBSOCKET_MAPPING.equals(s)) { + && !WEBSOCKET_MAPPING.equals(s) && !BackendGrpc.GRPC_SERVICE.equals(s)) { String name = v.getString("value").trim(); if (name.length() > 0) { return name; @@ -1424,6 +1439,7 @@ private Bean factoryBean(Bean owner, MethodInfo m) { collectJobs(bean); collectTools(bean); BackendGraphQL.collect(this, bean); + BackendGrpc.collect(this, bean); collectManaged(bean); } AnnotationValues props = m.getAnnotation(CONFIG_PROPERTIES); @@ -4041,7 +4057,7 @@ private static boolean callsFromWiring(MethodInfo m) { return m.getAnnotation(AUTOWIRED) != null || m.getAnnotation(POST_CONSTRUCT) != null || m.getAnnotation(PRE_DESTROY) != null || m.getAnnotation(BEAN) != null || m.getAnnotation(SCHEDULED) != null || m.getAnnotation(MCP_TOOL) != null - || BackendGraphQL.isMapping(m) + || BackendGraphQL.isMapping(m) || BackendGrpc.isRpc(m) || m.getAnnotation(MANAGED_ATTRIBUTE) != null || m.getAnnotation(MANAGED_OPERATION) != null; } @@ -4069,6 +4085,7 @@ private void emit() throws ProcessingException { } BackendSources writer = new BackendSources(this); BackendGraphQL.emit(this, sources); + BackendGrpc.emit(this, sources); if (ctx.hasErrors()) { return; } diff --git a/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendGrpc.java b/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendGrpc.java new file mode 100644 index 00000000000..e8ff5fe7bab --- /dev/null +++ b/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendGrpc.java @@ -0,0 +1,341 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.maven.processors; + +import com.codename1.maven.annotations.AnnotatedClass; +import com.codename1.maven.annotations.AnnotationValues; +import com.codename1.maven.annotations.MethodInfo; +import org.objectweb.asm.Type; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/// The gRPC services of a backend: every `@GrpcService` bean's `@Rpc` methods, +/// checked here, and an adapter per bean that registers them on the server's +/// `GrpcServer` with direct calls. The shape of each RPC comes from its +/// signature; see `GrpcService`. +final class BackendGrpc { + static final String GRPC_SERVICE = BackendBeans.PKG + "GrpcService;"; + static final String RPC = "Lcom/codename1/annotations/grpc/Rpc;"; + private static final String ITERATOR = "Ljava/util/Iterator;"; + private static final String OBSERVER = "Lcom/codename1/backend/grpc/StreamObserver;"; + private static final String CONTEXT = "Lcom/codename1/backend/grpc/GrpcContext;"; + private static final String G = "com.codename1.backend.grpc."; + + static final int UNARY = 0; + static final int SERVER_STREAMING = 1; + static final int CLIENT_STREAMING = 2; + static final int BIDI = 3; + + /// One RPC method. + static final class Rpc { + final MethodInfo method; + final String where; + String service; + String name; + int kind; + /// Binary names of the message classes. + String request; + String response; + boolean context; + + Rpc(MethodInfo method, String where) { + this.method = method; + this.where = where; + } + } + + private BackendGrpc() { + } + + static boolean isRpc(MethodInfo m) { + return m.getAnnotation(RPC) != null; + } + + /// The @Rpc on a method of the same name and descriptor declared by an + /// interface `cls` or one of its superclasses implements, or null. + private static AnnotationValues fromInterfaces(BackendBeans model, AnnotatedClass cls, + String key, int depth) { + for (AnnotatedClass c = cls; c != null && depth < 64; depth++) { + for (String i : c.getInterfaceInternalNames()) { + AnnotatedClass ic = RestControllerAnnotationProcessor.resolveClass(model.ctx, i); + if (ic == null) { + continue; + } + for (MethodInfo im : ic.getMethods()) { + if (key.equals(im.getName() + im.getDescriptor()) + && im.getAnnotation(RPC) != null) { + return im.getAnnotation(RPC); + } + } + AnnotationValues deeper = fromInterfaces(model, ic, key, depth + 1); + if (deeper != null) { + return deeper; + } + } + String sup = c.getSuperInternalName(); + c = sup == null || "java/lang/Object".equals(sup) ? null + : RestControllerAnnotationProcessor.resolveClass(model.ctx, sup); + } + return null; + } + + static void collect(BackendBeans model, BackendBeans.Bean bean) { + AnnotatedClass cls = bean.cls; + if (cls == null) { + return; + } + AnnotationValues onClass = cls.getClassAnnotation(GRPC_SERVICE); + if (onClass == null) { + return; + } + String service = onClass.getStringOrDefault("value", "").trim(); + if (service.length() == 0) { + model.ctx.error(cls, "@GrpcService on " + cls.getSourceName() + + " needs the service name, @GrpcService(\"package.Service\")"); + return; + } + for (MethodInfo m : model.inheritedMembers(cls)) { + AnnotationValues a = m.getAnnotation(RPC); + if (a == null && !m.isStatic()) { + // An implementation of a generated service interface: the @Rpc + // is on the interface's method, which an override never inherits. + a = fromInterfaces(model, cls, m.getName() + m.getDescriptor(), 0); + } + if (a == null) { + continue; + } + Rpc r = new Rpc(m, cls.getSourceName() + "." + m.getName()); + String override = a.getStringOrDefault("service", "").trim(); + r.service = override.length() > 0 ? override : service; + r.name = a.getStringOrDefault("value", "").trim(); + if (shape(model, cls, r)) { + bean.grpc.add(r); + } + } + if (bean.grpc.isEmpty()) { + model.ctx.error(cls, "@GrpcService " + cls.getSourceName() + + " has no @Rpc methods, so it would serve nothing"); + } + } + + private static boolean shape(BackendBeans model, AnnotatedClass cls, Rpc r) { + MethodInfo m = r.method; + String head = "@Rpc method " + r.where; + if (r.name.length() == 0) { + model.ctx.error(cls, head + " needs the method name, @Rpc(\"Method\")"); + return false; + } + if (m.isStatic()) { + model.ctx.error(cls, head + " is static; an RPC is an instance method of the bean"); + return false; + } + Type[] params = Type.getArgumentTypes(m.getDescriptor()); + String[] generic = RestClientAnnotationProcessor.parseGenericParameterSignatures( + m.getSignature(), params.length); + int n = params.length; + if (n > 0 && CONTEXT.equals(params[n - 1].getDescriptor())) { + r.context = true; + n--; + } + Type ret = Type.getReturnType(m.getDescriptor()); + String usage = " Expected one of: R m(Q), void m(Q, StreamObserver), " + + "R m(Iterator), void m(Iterator, StreamObserver), each optionally " + + "followed by a GrpcContext, where Q and R are @ProtoMessage classes."; + boolean streamIn = n >= 1 && ITERATOR.equals(params[0].getDescriptor()); + boolean streamOut = n == 2 && OBSERVER.equals(params[1].getDescriptor()); + if (n < 1 || n > 2 || (n == 2 && !streamOut)) { + model.ctx.error(cls, head + " has a signature gRPC cannot serve." + usage); + return false; + } + r.request = streamIn ? message(generic, 0) : className(params[0]); + if (streamOut) { + if (ret.getSort() != Type.VOID) { + model.ctx.error(cls, head + " streams its responses to a StreamObserver, so it " + + "returns void."); + return false; + } + r.response = message(generic, 1); + r.kind = streamIn ? BIDI : SERVER_STREAMING; + } else { + if (ret.getSort() != Type.OBJECT) { + model.ctx.error(cls, head + " returns no message." + usage); + return false; + } + r.response = ret.getClassName(); + r.kind = streamIn ? CLIENT_STREAMING : UNARY; + } + if (r.request == null || r.response == null) { + model.ctx.error(cls, head + " leaves a message type unnamed: declare Iterator and " + + "StreamObserver with the message classes, not raw types."); + return false; + } + if (r.request.startsWith("java.") || r.response.startsWith("java.")) { + model.ctx.error(cls, head + " uses a JDK type as a message; gRPC messages are " + + "@ProtoMessage classes."); + return false; + } + return true; + } + + private static String className(Type t) { + return t.getSort() == Type.OBJECT ? t.getClassName() : null; + } + + private static String message(String[] generic, int index) { + if (generic == null) { + return null; + } + String arg = BackendGraphQL.typeArgument(generic[index], 0); + if (arg != null && (arg.startsWith("+") || arg.startsWith("-"))) { + arg = arg.substring(1); // Iterator, StreamObserver + } + if (arg == null || !arg.startsWith("L")) { + return null; + } + return BackendGraphQL.erase(arg).substring(1, BackendGraphQL.erase(arg).length() - 1) + .replace('/', '.'); + } + + // ------------------------------------------------------------------- emit + + static void emit(BackendBeans model, Map sources) { + List paths = new ArrayList(); + for (BackendBeans.Bean b : model.beans) { + for (Rpc r : b.grpc) { + String path = "/" + r.service + "/" + r.name; + if (paths.contains(path)) { + model.ctx.error(b.cls, "@Rpc method " + r.where + " serves " + path + + ", which another @Rpc method already serves."); + } + paths.add(path); + } + } + if (model.ctx.hasErrors()) { + return; + } + name(model); + for (BackendBeans.Bean b : model.beans) { + if (b.grpcAdapter != null) { + sources.put(b.grpcAdapter, adapter(b)); + } + } + } + + static void name(BackendBeans model) { + for (BackendBeans.Bean b : model.beans) { + if (!b.grpc.isEmpty()) { + String pkg = RestClientAnnotationProcessor.packageOf(b.type.replace('/', '.')); + b.grpcAdapter = BackendBeans.qualify(pkg, BackendBeans.baseName(b.type) + "Cn1Grpc"); + } + } + } + + static boolean any(BackendBeans model) { + for (BackendBeans.Bean b : model.beans) { + if (b.grpcAdapter != null) { + return true; + } + } + return false; + } + + private static String codec(String binary) { + // ProtoMessageAnnotationProcessor writes the codec as a top-level class + // named after the binary name, so p.Outer$Inner's is p.Outer$InnerProtoCodec. + return binary + "ProtoCodec.INSTANCE"; + } + + static String adapter(BackendBeans.Bean b) { + String binary = b.grpcAdapter; + String name = binary.substring(binary.lastIndexOf('.') + 1); + String type = b.cls.getSourceName(); + StringBuilder sb = new StringBuilder(); + String pkg = RestClientAnnotationProcessor.packageOf(binary); + if (pkg.length() > 0) { + sb.append("package ").append(pkg).append(";\n\n"); + } + sb.append("// Generated from the @Rpc methods of ").append(b.cls.getBinaryName()) + .append(". Do not edit.\n"); + sb.append("@com.codename1.backend.annotations.Generated\n"); + sb.append("@SuppressWarnings({\"unchecked\", \"rawtypes\"})\n"); + sb.append("public final class ").append(name).append(" {\n"); + sb.append(" private final ").append(type).append(" target;\n\n"); + sb.append(" public ").append(name).append('(').append(type) + .append(" target) {\n this.target = target;\n }\n\n"); + sb.append(" public void register(").append(G).append("GrpcServer s) {\n"); + for (Rpc r : b.grpc) { + String call = "target." + (BackendBeans.bridged(r.method) + ? BackendWeaver.bridge(r.method.getName()) : r.method.getName()); + String ctx = r.context ? ", c" : ""; + String svc = BackendSources.quote(r.service); + String mname = BackendSources.quote(r.name); + String codecs = codec(r.request) + ", " + codec(r.response); + switch (r.kind) { + case UNARY: + sb.append(" s.add(").append(G).append("GrpcMethod.unary(").append(svc) + .append(", ").append(mname).append(", ").append(codecs).append(",\n") + .append(" new ").append(G).append("GrpcMethod.Unary() {\n") + .append(" public Object call(Object q, ").append(G) + .append("GrpcContext c) throws Exception {\n") + .append(" return ").append(call).append("((") + .append(r.request.replace('$', '.')).append(") q").append(ctx).append(");\n") + .append(" }\n }));\n"); + break; + case SERVER_STREAMING: + sb.append(" s.add(").append(G).append("GrpcMethod.serverStreaming(").append(svc) + .append(", ").append(mname).append(", ").append(codecs).append(",\n") + .append(" new ").append(G).append("GrpcMethod.ServerStreaming() {\n") + .append(" public void call(Object q, ").append(G) + .append("StreamObserver o, ").append(G) + .append("GrpcContext c) throws Exception {\n") + .append(" ").append(call).append("((") + .append(r.request.replace('$', '.')).append(") q, o").append(ctx).append(");\n") + .append(" }\n }));\n"); + break; + case CLIENT_STREAMING: + sb.append(" s.add(").append(G).append("GrpcMethod.clientStreaming(").append(svc) + .append(", ").append(mname).append(", ").append(codecs).append(",\n") + .append(" new ").append(G).append("GrpcMethod.ClientStreaming() {\n") + .append(" public Object call(java.util.Iterator q, ").append(G) + .append("GrpcContext c) throws Exception {\n") + .append(" return ").append(call).append("(q").append(ctx).append(");\n") + .append(" }\n }));\n"); + break; + default: + sb.append(" s.add(").append(G).append("GrpcMethod.bidiStreaming(").append(svc) + .append(", ").append(mname).append(", ").append(codecs).append(",\n") + .append(" new ").append(G).append("GrpcMethod.BidiStreaming() {\n") + .append(" public void call(java.util.Iterator q, ").append(G) + .append("StreamObserver o, ").append(G) + .append("GrpcContext c) throws Exception {\n") + .append(" ").append(call).append("(q, o").append(ctx).append(");\n") + .append(" }\n }));\n"); + break; + } + } + sb.append(" }\n}\n"); + return sb.toString(); + } +} diff --git a/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendWiringWriter.java b/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendWiringWriter.java index b2bb4bc188c..9d0910235aa 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendWiringWriter.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/processors/BackendWiringWriter.java @@ -397,6 +397,7 @@ private void create(StringBuilder sb, List routers) { .append(");\n }\n }\n }\n"); } graphQL(sb); + grpc(sb); if (Boolean.TRUE.equals(model.ctx.getAttribute("cn1.backend.mvc"))) { sb.append(" handlers.add(new com.codename1.generated.mvc.Assets());\n"); } @@ -444,6 +445,29 @@ private void graphQL(StringBuilder sb) { sb.append(" handlers.add(graphQL);\n }\n"); } + /// The gRPC server: every `@GrpcService` bean's methods on one GrpcServer, + /// which is also a handler (gRPC-Web over HTTP/1.1) and which the server + /// finds among the handlers for native gRPC on HTTP/2. + private void grpc(StringBuilder sb) { + if (!BackendGrpc.any(model)) { + return; + } + sb.append(" {\n com.codename1.backend.grpc.GrpcServer grpc = " + + "new com.codename1.backend.grpc.GrpcServer();\n"); + for (BackendBeans.Bean b : model.beans) { + if (b.grpcAdapter == null) { + continue; + } + String ref = "serving" + b.var; + sb.append(" ").append(typeOf(b)).append(' ').append(ref).append(" = ") + .append(reference(b)).append(";\n"); + sb.append(" if (").append(ref).append(" != null) {\n"); + sb.append(" new ").append(b.grpcAdapter).append('(').append(ref) + .append(").register(grpc);\n }\n"); + } + sb.append(" handlers.add(grpc);\n }\n"); + } + /// `if (condition) {` before a conditional bean's statement, nothing otherwise. private void openCondition(StringBuilder sb, BackendBeans.Bean b) { if (!b.isConditional()) { diff --git a/maven/build-engine/src/main/java/com/codename1/maven/processors/RestControllerAnnotationProcessor.java b/maven/build-engine/src/main/java/com/codename1/maven/processors/RestControllerAnnotationProcessor.java index ee26ba05e09..b43d5f798a1 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/processors/RestControllerAnnotationProcessor.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/processors/RestControllerAnnotationProcessor.java @@ -381,6 +381,8 @@ public Set getAnnotationDescriptors() { out.add(CONTROLLER); out.add(MVC_CONTROLLER); out.add(WEBSOCKET_MAPPING); + // A module whose only endpoints are gRPC services still needs the wiring. + out.add(BackendGrpc.GRPC_SERVICE); out.add(BackendExceptionHandlers.CONTROLLER_ADVICE); out.add(BackendExceptionHandlers.REST_CONTROLLER_ADVICE); return out; @@ -1802,7 +1804,7 @@ public void finish(ProcessorContext ctx) throws ProcessingException { // would start its listeners. if (controllers.isEmpty() && webSockets.isEmpty() && !beans.hasJobs() && !beans.hasListeners() && !beans.hasTools() && !beans.hasManaged() - && !beans.hasGraphQL() && !settings.management + && !beans.hasGraphQL() && !beans.hasGrpc() && !settings.management && !staticFiles) { // NOTHING LEFT, so a marker from an earlier build has to go. Maven // keeps target/classes across a build without clean, and returning diff --git a/maven/build-engine/src/test/java/com/codename1/maven/processors/BackendBeansTest.java b/maven/build-engine/src/test/java/com/codename1/maven/processors/BackendBeansTest.java index 32923d7e31c..16a640e36e5 100644 --- a/maven/build-engine/src/test/java/com/codename1/maven/processors/BackendBeansTest.java +++ b/maven/build-engine/src/test/java/com/codename1/maven/processors/BackendBeansTest.java @@ -4177,6 +4177,178 @@ public void graphQLControllersAreWiredToTheEndpoint() throws Exception { } } + private static final String GRPC_IMPORTS = "import com.codename1.backend.grpc.*;\n" + + "import com.codename1.annotations.grpc.Rpc;\n" + + "import com.codename1.io.grpc.*;\n"; + + private static Map grpcSample() { + Map s = new LinkedHashMap(); + s.put("com.example.Msg", PKG + "public class Msg {\n" + + " public String text;\n public Msg() {}\n" + + " public Msg(String t) { text = t; }\n}\n"); + // What ProtoMessageAnnotationProcessor writes for a one-field message. + s.put("com.example.MsgProtoCodec", PKG + GRPC_IMPORTS + + "public final class MsgProtoCodec implements ProtoCodec {\n" + + " public static final MsgProtoCodec INSTANCE = new MsgProtoCodec();\n" + + " public void write(ProtoWriter w, Msg m) throws java.io.IOException {\n" + + " if (m.text != null) { w.writeString(1, m.text); }\n }\n" + + " public Msg read(ProtoReader r) throws java.io.IOException {\n" + + " Msg m = new Msg();\n" + + " while (!r.isAtEnd()) { int t = r.readTag();\n" + + " if (t >>> 3 == 1) { m.text = r.readString(); } else { r.skipField(t); } }\n" + + " return m;\n }\n}\n"); + s.put("com.example.Echo", PKG + GRPC_IMPORTS + + "@GrpcService(\"test.Echo\") public class Echo {\n" + + " @Rpc(\"Say\") public Msg say(Msg m, GrpcContext c) {\n" + + " return new Msg(\"hello \" + m.text + \" \" + c.getMethod());\n }\n" + + " @Rpc(\"Count\") void count(Msg m, StreamObserver out) {\n" + + " for (int i = 0; i < Integer.parseInt(m.text); i++) { out.onNext(new Msg(\"n\" + i)); }\n" + + " }\n" + + " @Rpc(\"Join\") public Msg join(Iterator in) {\n" + + " StringBuilder b = new StringBuilder();\n" + + " while (in.hasNext()) { b.append(in.next().text); }\n" + + " return new Msg(b.toString());\n }\n" + + " @Rpc(\"Chat\") public void chat(Iterator in, StreamObserver out) {\n" + + " while (in.hasNext()) { out.onNext(new Msg(\"re:\" + in.next().text)); }\n" + + " }\n}\n"); + return s; + } + + @Test + public void grpcServicesAreWiredToTheServer() throws Exception { + File classes = compile(grpcSample()); + ProcessorContext ctx = process(classes); + assertNoErrors(ctx); + URLClassLoader loader = new URLClassLoader(new URL[] {classes.toURI().toURL()}, + getClass().getClassLoader()); + BackendApplication app = (BackendApplication) loader + .loadClass("com.example.BackendWiring").newInstance(); + int port = freePort(); + Properties settings = new Properties(); + settings.setProperty(Config.SERVER_PORT, String.valueOf(port)); + Backend backend = withApplication(Backend.builder(Config.of(settings, "dev")).quiet(), app) + .start(); + try { + com.codename1.io.grpc.ProtoCodec codec = (com.codename1.io.grpc.ProtoCodec) loader + .loadClass("com.example.MsgProtoCodec").getField("INSTANCE").get(null); + Class msg = loader.loadClass("com.example.Msg"); + java.lang.reflect.Field text = msg.getField("text"); + com.codename1.backend.grpc.GrpcChannel ch = + com.codename1.backend.grpc.GrpcChannel.forTarget("http://127.0.0.1:" + port); + Object said = ch.unary("/test.Echo/Say", codec, codec, + msg.getConstructor(String.class).newInstance("you")); + assertEquals("hello you /test.Echo/Say", text.get(said)); + com.codename1.backend.grpc.GrpcChannel.Call call = ch.serverStreaming( + "/test.Echo/Count", codec, codec, msg.getConstructor(String.class).newInstance("3")); + List got = new ArrayList(); + while (call.hasNext()) { + got.add(text.get(call.next())); + } + call.close(); + assertEquals(Arrays.asList("n0", "n1", "n2"), got); + List parts = new ArrayList(); + for (String p : new String[] {"a", "b"}) { + parts.add(msg.getConstructor(String.class).newInstance(p)); + } + assertEquals("ab", text.get(ch.clientStreaming("/test.Echo/Join", codec, codec, + parts.iterator()))); + com.codename1.backend.grpc.GrpcChannel.Call chat = + ch.bidiStreaming("/test.Echo/Chat", codec, codec); + chat.send(msg.getConstructor(String.class).newInstance("x")); + chat.complete(); + assertEquals("re:x", text.get(chat.next())); + assertFalse(chat.hasNext()); + chat.close(); + } finally { + backend.stop(); + } + } + + @Test + public void grpcServiceInterfacesFromTheProtoGeneratorAreServed() throws Exception { + Map s = grpcSample(); + s.remove("com.example.Echo"); + // The shape cn1:generate-grpc -Dcn1.grpc.target=backend writes. + s.put("com.example.EchoService", PKG + GRPC_IMPORTS + + "public interface EchoService {\n" + + " @Rpc(value = \"Say\", service = \"test.Echo\") Msg say(Msg request);\n}\n"); + s.put("com.example.EchoImpl", PKG + GRPC_IMPORTS + + "@GrpcService(\"test.Echo\") public class EchoImpl implements EchoService {\n" + + " public Msg say(Msg m) { return new Msg(\"impl \" + m.text); }\n}\n"); + File classes = compile(s); + ProcessorContext ctx = process(classes); + assertNoErrors(ctx); + URLClassLoader loader = new URLClassLoader(new URL[] {classes.toURI().toURL()}, + getClass().getClassLoader()); + BackendApplication app = (BackendApplication) loader + .loadClass("com.example.BackendWiring").newInstance(); + int port = freePort(); + Properties settings = new Properties(); + settings.setProperty(Config.SERVER_PORT, String.valueOf(port)); + Backend backend = withApplication(Backend.builder(Config.of(settings, "dev")).quiet(), app) + .start(); + try { + com.codename1.io.grpc.ProtoCodec codec = (com.codename1.io.grpc.ProtoCodec) loader + .loadClass("com.example.MsgProtoCodec").getField("INSTANCE").get(null); + Class msg = loader.loadClass("com.example.Msg"); + Object said = com.codename1.backend.grpc.GrpcChannel.forTarget("http://127.0.0.1:" + port) + .unary("/test.Echo/Say", codec, codec, + msg.getConstructor(String.class).newInstance("x")); + assertEquals("impl x", msg.getField("text").get(said)); + } finally { + backend.stop(); + } + } + + @Test + public void grpcServicesTakeNestedMessagesAndWildcards() throws Exception { + // A static nested message's codec is the top-level class + // ProtoMessageAnnotationProcessor writes, Outer$InnerProtoCodec, and a + // wildcard type argument names its message like a plain one. + Map s = new LinkedHashMap(); + s.put("com.example.Outer", PKG + "public class Outer {\n" + + " public static class Inner { public String text; }\n}\n"); + s.put("com.example.Outer$InnerProtoCodec", PKG + GRPC_IMPORTS + + "public final class Outer$InnerProtoCodec implements ProtoCodec {\n" + + " public static final Outer$InnerProtoCodec INSTANCE = new Outer$InnerProtoCodec();\n" + + " public void write(ProtoWriter w, Outer.Inner m) throws java.io.IOException {}\n" + + " public Outer.Inner read(ProtoReader r) throws java.io.IOException {\n" + + " while (!r.isAtEnd()) { r.skipField(r.readTag()); }\n" + + " return new Outer.Inner();\n }\n}\n"); + s.put("com.example.Nested", PKG + GRPC_IMPORTS + + "@GrpcService(\"test.Nested\") public class Nested {\n" + + " @Rpc(\"Say\") public Outer.Inner say(Outer.Inner m) { return m; }\n" + + " @Rpc(\"Many\") public void many(Iterator in,\n" + + " StreamObserver out) {}\n}\n"); + File classes = compile(s); + ProcessorContext ctx = process(classes); + assertNoErrors(ctx); + URLClassLoader loader = new URLClassLoader(new URL[] {classes.toURI().toURL()}, + getClass().getClassLoader()); + assertTrue(loader.loadClass("com.example.BackendWiring") != null); + } + + @Test + public void grpcMethodsGrpcCannotServeFailTheBuild() throws Exception { + Map s = grpcSample(); + s.put("com.example.Bad", PKG + GRPC_IMPORTS + + "@GrpcService(\"test.Bad\") public class Bad {\n" + + " @Rpc(\"Two\") public Msg two(Msg a, Msg b) { return a; }\n" + + " @Rpc(\"Ret\") public Msg ret(Msg a, StreamObserver o) { return a; }\n" + + " @Rpc(\"Raw\") public Msg raw(Iterator in) { return null; }\n" + + "}\n"); + String errors = String.valueOf(process(compile(s)).getErrors()); + assertTrue(errors, errors.contains("Bad.two has a signature gRPC cannot serve")); + assertTrue(errors, errors.contains("Bad.ret streams its responses")); + assertTrue(errors, errors.contains("Bad.raw leaves a message type unnamed")); + s = grpcSample(); + s.put("com.example.Dup", PKG + GRPC_IMPORTS + + "@GrpcService(\"test.Echo\") public class Dup {\n" + + " @Rpc(\"Say\") public Msg say(Msg a) { return a; }\n}\n"); + errors = String.valueOf(process(compile(s)).getErrors()); + assertTrue(errors, errors.contains("serves /test.Echo/Say, which another @Rpc method")); + } + @Test public void graphQLMappingsTheSchemaLacksFailTheBuild() throws Exception { Map s = new LinkedHashMap(); diff --git a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/GenerateGrpcMojo.java b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/GenerateGrpcMojo.java index 9df796d9b3d..f48fec7799d 100644 --- a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/GenerateGrpcMojo.java +++ b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/GenerateGrpcMojo.java @@ -65,9 +65,20 @@ /// callback. A `static of(String baseUrl)` factory wires the /// interface to the runtime registry. /// -/// Streaming RPCs (`stream` keyword on request or response) are not -/// supported in this release and produce a build error pointing at -/// the offending line. +/// Streaming RPCs (`stream` keyword on request or response) are a build +/// error pointing at the offending line in this mode, since the +/// application client is unary only. +/// +/// With `-Dcn1.grpc.target=backend` the services are generated for a +/// Codename One backend instead, and all four RPC shapes are accepted: +/// +/// - one `Service` interface per `service`, whose methods carry +/// `@Rpc`. A `@GrpcService("package.Service")` class that implements it +/// serves the service; the build wires it to the gRPC server. +/// - one `Client` class per `service`, calling it through a +/// `GrpcChannel`: unary methods return the response, server streaming +/// returns an `Iterator`, client streaming takes one, and bidirectional +/// streaming returns the open `GrpcChannel.Call`. @Mojo(name = "generate-grpc", defaultPhase = LifecyclePhase.NONE, requiresProject = true, @@ -99,6 +110,11 @@ public class GenerateGrpcMojo extends AbstractMojo { /// When `true` (default) existing files at the destination are /// overwritten. Pass `-Dcn1.grpc.overwrite=false` to keep your /// hand-edits and only emit missing files. + /// `client` (the default) for an application's `@GrpcClient`, or + /// `backend` for a backend's service interface and client. + @Parameter(property = "cn1.grpc.target", defaultValue = "client") + String grpcTarget; + @Parameter(property = "cn1.grpc.overwrite", defaultValue = "true") private boolean overwrite; @@ -131,6 +147,7 @@ public void execute() throws MojoExecutionException, MojoFailureException { ProtoFile parsed; try { parsed = new ProtoParser(source, protoFile.getName()).parseFile(); + parsed.fileName = protoFile.getName(); } catch (ProtoParseException ppe) { throw new MojoFailureException(ppe.getMessage(), ppe); } @@ -141,8 +158,15 @@ public void execute() throws MojoExecutionException, MojoFailureException { + " basePackage=" + effectivePackage + " protoPackage=" + (parsed.protoPackage == null ? "(none)" : parsed.protoPackage)); + String mode = effective(grpcTarget, "cn1.grpc.target"); + boolean backend = "backend".equals(mode); + if (!backend && mode != null && mode.length() > 0 && !"client".equals(mode)) { + throw new MojoFailureException("cn1.grpc.target is '" + mode + + "'; use client or backend"); + } Generator gen = new Generator(parsed, effectivePackage, outputDirectory, overwrite, emitRecords, getLog()); + gen.backend = backend; try { gen.run(); } catch (IOException ioe) { @@ -173,6 +197,7 @@ private String detectJavaTargetString() { static final class ProtoFile { String protoPackage; // e.g. "helloworld" + String fileName; final List messages = new ArrayList(); final List enums = new ArrayList(); final List services = new ArrayList(); @@ -211,6 +236,9 @@ static final class ProtoRpc { String name; String requestType; String responseType; + boolean clientStreaming; + boolean serverStreaming; + int line; } static final class ProtoParseException extends RuntimeException { @@ -399,9 +427,10 @@ private ProtoRpc parseRpc(String serviceName) { r.name = readIdent(); expect('('); skipWhitespaceAndComments(); + r.line = line; if (peek("stream")) { - throw err("Streaming RPCs are not supported in this release " - + "(service " + serviceName + ".rpc " + r.name + ")"); + consume("stream"); + r.clientStreaming = true; } r.requestType = readDottedIdent(); expect(')'); @@ -410,8 +439,8 @@ private ProtoRpc parseRpc(String serviceName) { expect('('); skipWhitespaceAndComments(); if (peek("stream")) { - throw err("Streaming RPCs are not supported in this release " - + "(service " + serviceName + ".rpc " + r.name + ")"); + consume("stream"); + r.serverStreaming = true; } r.responseType = readDottedIdent(); expect(')'); @@ -561,6 +590,8 @@ static final class Generator { private final boolean overwrite; private final boolean emitRecords; private final org.apache.maven.plugin.logging.Log log; + /// Generate for a backend: a service interface and a GrpcChannel client. + boolean backend; /// Simple-name -> kind ("message" | "enum"). Lets a field type /// like `Status` (an enum) emit a different ProtoField shape @@ -599,7 +630,20 @@ void run() throws IOException { emitEnum(pkgDir, e, basePackage); } for (ProtoService s : file.services) { - emitService(pkgDir, s); + if (backend) { + emitBackendService(pkgDir, s); + emitBackendClient(pkgDir, s); + } else { + for (ProtoRpc rpc : s.rpcs) { + if (rpc.clientStreaming || rpc.serverStreaming) { + throw new ProtoParseException(file.fileName + ":" + rpc.line + + ": streaming RPCs are not supported by the application " + + "client (service " + s.name + ".rpc " + rpc.name + + "); generate with -Dcn1.grpc.target=backend for a backend"); + } + } + emitService(pkgDir, s); + } } log.info("Generated " + file.messages.size() + " @ProtoMessage class(es), " @@ -783,6 +827,97 @@ private void emitService(File dir, ProtoService s) throws IOException { writeFile(f, sb.toString()); } + private String serviceFqn(ProtoService s) { + return file.protoPackage == null || file.protoPackage.length() == 0 + ? s.name : file.protoPackage + "." + s.name; + } + + private void emitBackendService(File dir, ProtoService s) throws IOException { + String className = s.name + "Service"; + File f = new File(dir, className + ".java"); + if (f.exists() && !overwrite) { + return; + } + String fqn = escapeJava(serviceFqn(s)); + StringBuilder sb = new StringBuilder(2048); + sb.append("// Generated by cn1:generate-grpc.\n"); + sb.append("package ").append(basePackage).append(";\n\n"); + sb.append("import com.codename1.annotations.grpc.Rpc;\n"); + sb.append("import com.codename1.backend.grpc.StreamObserver;\n"); + sb.append("import java.util.Iterator;\n\n"); + sb.append("/// The `").append(fqn).append("` service. Serve it from a bean:\n"); + sb.append("///\n/// ```java\n/// @GrpcService(\"").append(fqn) + .append("\")\n/// public class ").append(s.name).append("Impl implements ") + .append(className).append(" { ... }\n/// ```\n"); + sb.append("public interface ").append(className).append(" {\n"); + Set used = new LinkedHashSet(); + for (ProtoRpc rpc : s.rpcs) { + String m = uniqueName(lowerFirst(rpc.name), used); + String q = resolveMessageType(rpc.requestType); + String a = resolveMessageType(rpc.responseType); + sb.append("\n @Rpc(value = \"").append(escapeJava(rpc.name)) + .append("\", service = \"").append(fqn).append("\")\n "); + if (rpc.serverStreaming) { + sb.append("void ").append(m).append('(') + .append(rpc.clientStreaming ? "Iterator<" + q + "> requests" : q + " request") + .append(", StreamObserver<").append(a).append("> responses);\n"); + } else { + sb.append(a).append(' ').append(m).append('(') + .append(rpc.clientStreaming ? "Iterator<" + q + "> requests" : q + " request") + .append(");\n"); + } + } + sb.append("}\n"); + writeFile(f, sb.toString()); + } + + private void emitBackendClient(File dir, ProtoService s) throws IOException { + String className = s.name + "Client"; + File f = new File(dir, className + ".java"); + if (f.exists() && !overwrite) { + return; + } + String fqn = escapeJava(serviceFqn(s)); + StringBuilder sb = new StringBuilder(2048); + sb.append("// Generated by cn1:generate-grpc.\n"); + sb.append("package ").append(basePackage).append(";\n\n"); + sb.append("import com.codename1.backend.grpc.GrpcChannel;\n"); + sb.append("import java.util.Iterator;\n\n"); + sb.append("/// Calls the `").append(fqn).append("` service through a channel.\n"); + sb.append("public final class ").append(className).append(" {\n"); + sb.append(" private final GrpcChannel channel;\n\n"); + sb.append(" public ").append(className).append("(GrpcChannel channel) {\n"); + sb.append(" this.channel = channel;\n }\n"); + Set used = new LinkedHashSet(); + for (ProtoRpc rpc : s.rpcs) { + String m = uniqueName(lowerFirst(rpc.name), used); + String q = resolveMessageType(rpc.requestType); + String a = resolveMessageType(rpc.responseType); + String path = "\"/" + fqn + "/" + escapeJava(rpc.name) + "\""; + String codecs = q + "ProtoCodec.INSTANCE, " + a + "ProtoCodec.INSTANCE"; + sb.append('\n'); + if (rpc.clientStreaming && rpc.serverStreaming) { + sb.append(" public GrpcChannel.Call<").append(q).append(", ").append(a) + .append("> ").append(m).append("() {\n return channel.bidiStreaming(") + .append(path).append(", ").append(codecs).append(");\n }\n"); + } else if (rpc.serverStreaming) { + sb.append(" public Iterator<").append(a).append("> ").append(m).append('(') + .append(q).append(" request) {\n return channel.serverStreaming(") + .append(path).append(", ").append(codecs).append(", request);\n }\n"); + } else if (rpc.clientStreaming) { + sb.append(" public ").append(a).append(' ').append(m).append("(Iterator<") + .append(q).append("> requests) {\n return channel.clientStreaming(") + .append(path).append(", ").append(codecs).append(", requests);\n }\n"); + } else { + sb.append(" public ").append(a).append(' ').append(m).append('(').append(q) + .append(" request) {\n return channel.unary(").append(path) + .append(", ").append(codecs).append(", request);\n }\n"); + } + } + sb.append("}\n"); + writeFile(f, sb.toString()); + } + private void emitRpcMethod(StringBuilder sb, ProtoRpc rpc, Set usedNames) { String methodName = uniqueName(lowerFirst(rpc.name), usedNames); String reqType = resolveMessageType(rpc.requestType); diff --git a/maven/codenameone-maven-plugin/src/test/java/com/codename1/maven/GenerateGrpcMojoTest.java b/maven/codenameone-maven-plugin/src/test/java/com/codename1/maven/GenerateGrpcMojoTest.java index 3874617b6bc..97ba45fc39e 100644 --- a/maven/codenameone-maven-plugin/src/test/java/com/codename1/maven/GenerateGrpcMojoTest.java +++ b/maven/codenameone-maven-plugin/src/test/java/com/codename1/maven/GenerateGrpcMojoTest.java @@ -1,5 +1,24 @@ /* * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.maven; @@ -124,15 +143,50 @@ void respectsOverwriteFalse(@TempDir Path tmp) throws Exception { } @Test - void streamingRpcRejected() { - String src = "syntax = \"proto3\"; service S { rpc R (stream Req) returns (Resp); }\n"; + void streamingRpcRejectedForTheApplicationClient(@TempDir Path tmp) { + String src = "syntax = \"proto3\";\nservice S {\n rpc R (stream Req) returns (Resp); }\n"; + GenerateGrpcMojo.ProtoFile parsed = parse(src); + parsed.fileName = "t.proto"; GenerateGrpcMojo.ProtoParseException ex = assertThrows( GenerateGrpcMojo.ProtoParseException.class, - () -> new GenerateGrpcMojo.ProtoParser(src, "t.proto").parseFile()); - assertTrue(ex.getMessage().contains("Streaming RPCs"), + () -> new GenerateGrpcMojo.Generator(parsed, "com.example", tmp.toFile(), true, + true, new SystemStreamLog()).run()); + assertTrue(ex.getMessage().contains("t.proto:3: streaming RPCs are not supported"), "expected streaming rejection; got: " + ex.getMessage()); } + private static final String STREAMING_PROTO = "syntax = \"proto3\";\npackage test;\n" + + "message Msg { string text = 1; }\n" + + "service Echo {\n" + + " rpc Say (Msg) returns (Msg);\n" + + " rpc Count (Msg) returns (stream Msg);\n" + + " rpc Join (stream Msg) returns (Msg);\n" + + " rpc Chat (stream Msg) returns (stream Msg);\n" + + "}\n"; + + @Test + void backendTargetEmitsAServiceInterfaceAndAClient(@TempDir Path tmp) throws Exception { + GenerateGrpcMojo.Generator gen = new GenerateGrpcMojo.Generator(parse(STREAMING_PROTO), + "com.example", tmp.toFile(), true, false, new SystemStreamLog()); + gen.backend = true; + gen.run(); + String svc = readString(tmp.toFile(), "com/example/EchoService.java"); + String m = "com.example.Msg"; + assertTrue(svc.contains("@Rpc(value = \"Say\", service = \"test.Echo\")\n " + + m + " say(" + m + " request);"), svc); + assertTrue(svc.contains("void count(" + m + " request, StreamObserver<" + m + + "> responses);"), svc); + assertTrue(svc.contains(m + " join(Iterator<" + m + "> requests);"), svc); + assertTrue(svc.contains("void chat(Iterator<" + m + "> requests, StreamObserver<" + m + + "> responses);"), svc); + String cli = readString(tmp.toFile(), "com/example/EchoClient.java"); + assertTrue(cli.contains("return channel.unary(\"/test.Echo/Say\", " + m + + "ProtoCodec.INSTANCE, " + m + "ProtoCodec.INSTANCE, request);"), cli); + assertTrue(cli.contains("public Iterator<" + m + "> count(" + m + " request)"), cli); + assertTrue(cli.contains("public " + m + " join(Iterator<" + m + "> requests)"), cli); + assertTrue(cli.contains("public GrpcChannel.Call<" + m + ", " + m + "> chat()"), cli); + } + @Test void snakeCaseFieldNameConversion() { assertEquals("emojiCode", GenerateGrpcMojo.Generator.javaName("emoji_code")); diff --git a/scripts/pre-push-gates.sh b/scripts/pre-push-gates.sh index ea515ef5d58..39da506a130 100755 --- a/scripts/pre-push-gates.sh +++ b/scripts/pre-push-gates.sh @@ -257,7 +257,15 @@ if selected website-docs; then --step "Test developer guide chapter generation" \ --step "Check developer guide links against the routes this site serves" if [ "$FULL" = 1 ]; then - gate "Hugo site build (scripts/website/build.sh)" scripts/website/build.sh + # As website-docs.yml runs it: against this checkout's snapshots, which is + # what switches the site apps (Skin Designer, Initializr) to JDK 17; without + # it they compile with JDK 8 and fail on "invalid target release". The build + # rewrites a tracked fetch timestamp and an unignored bundle; both are put + # back so a clean pass can be recorded. + gate "Hugo site build (scripts/website/build.sh)" env WEBSITE_BOOTSTRAP_CN1_SNAPSHOTS=true \ + JAVA17_HOME="$JDK17" scripts/website/build.sh + git checkout -q -- docs/website/data/cn1libs.json 2>/dev/null || true + rm -rf docs/website/static/skindesigner-app else skip "Hugo site build" "--full runs scripts/website/build.sh (local Hugo must match the CI pin)" fi diff --git a/scripts/website/build.sh b/scripts/website/build.sh index 07372271921..3374ce7af88 100755 --- a/scripts/website/build.sh +++ b/scripts/website/build.sh @@ -768,13 +768,13 @@ build_skindesigner_for_site() { # Ensure attached classifier artifact skindesigner-ZipSupport:jar:common # is present in the local Maven repo before building skindesigner-common. run_skindesigner_mvn -q -U -pl cn1libs/ZipSupport -am \ - "${skindesigner_workspace_args[@]}" \ + ${skindesigner_workspace_args[@]+"${skindesigner_workspace_args[@]}"} \ -DskipTests \ -Dcodename1.platform=javascript \ install run_skindesigner_mvn -q -U -pl javascript -am \ - "${skindesigner_workspace_args[@]}" \ + ${skindesigner_workspace_args[@]+"${skindesigner_workspace_args[@]}"} \ -DskipTests \ -Dautomated=true \ -Dcodename1.platform=javascript \ diff --git a/vm/backend/grpc-interop/interop.py b/vm/backend/grpc-interop/interop.py new file mode 100755 index 00000000000..9aa625c5b1d --- /dev/null +++ b/vm/backend/grpc-interop/interop.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# Licensed under the GNU General Public License version 2 with the Classpath +# Exception; see the LICENSE file at the root of this repository. +"""gRPC interop peer for the backend's gRPC server and client. + +Uses grpcio (gRPC C-core), the reference implementation, so the backend is +checked against a gRPC that is not its own. + + interop.py server PORT serve test.Echo until killed (prints READY) + interop.py client TARGET call test.Echo on TARGET (host:port), all shapes + +The service matches GrpcEndToEndTest: Say (unary), Count (server streaming), +Join (client streaming), Chat (bidi). Messages have one string field, 1. +""" +import sys +import time +from concurrent import futures + +import grpc + + +def enc(s): + b = s.encode("utf-8") + n, v = len(b), bytearray() + while True: + if n < 0x80: + v.append(n) + break + v.append((n & 0x7F) | 0x80) + n >>= 7 + return bytes([0x0A]) + bytes(v) + b + + +def dec(b): + if not b: + return "" + i, n, shift = 1, 0, 0 + while True: + c = b[i] + i += 1 + n |= (c & 0x7F) << shift + shift += 7 + if c < 0x80: + break + return b[i:i + n].decode("utf-8") + + +def say(req, ctx): + s = dec(req) + if s.startswith("fail:"): + ctx.abort(grpc.StatusCode.INVALID_ARGUMENT, s[5:]) + who = dict(ctx.invocation_metadata()).get("x-who") + ctx.set_trailing_metadata((("x-done", "yes"),)) + return enc("hello " + s + ("" if who is None else " from " + who)) + + +def count(req, ctx): + n = int(dec(req)) + for i in range(n): + yield enc("n%d" % i) + if n == 2: + ctx.abort(grpc.StatusCode.ABORTED, "stopped at two") + + +def join(reqs, ctx): + return enc("".join(dec(r) for r in reqs)) + + +def chat(reqs, ctx): + for r in reqs: + yield enc("re:" + dec(r)) + + +def serve(port): + ident = dict(request_deserializer=None, response_serializer=None) + handler = grpc.method_handlers_generic_handler("test.Echo", { + "Say": grpc.unary_unary_rpc_method_handler(say, **ident), + "Count": grpc.unary_stream_rpc_method_handler(count, **ident), + "Join": grpc.stream_unary_rpc_method_handler(join, **ident), + "Chat": grpc.stream_stream_rpc_method_handler(chat, **ident), + }) + server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) + server.add_generic_rpc_handlers((handler,)) + server.add_insecure_port("127.0.0.1:%d" % port) + server.start() + print("READY", flush=True) + while True: + time.sleep(3600) + + +def check(cond, what): + if not cond: + raise SystemExit("FAILED: " + what) + + +def client(target): + ch = grpc.insecure_channel(target) + say_ = ch.unary_unary("/test.Echo/Say") + count_ = ch.unary_stream("/test.Echo/Count") + join_ = ch.stream_unary("/test.Echo/Join") + chat_ = ch.stream_stream("/test.Echo/Chat") + + check(dec(say_(enc("py"))) == "hello py", "unary") + check(dec(say_(enc("m"), metadata=(("x-who", "py"),))) == "hello m from py", "metadata") + resp, call = say_.with_call(enc("t")) + check(dict(call.trailing_metadata()).get("x-done") == "yes", "trailer") + big = "x" * 300000 + check(dec(say_(enc(big), compression=grpc.Compression.Gzip)) == "hello " + big, "gzip") + try: + say_(enc("fail:bad input %")) + check(False, "status") + except grpc.RpcError as e: + check(e.code() == grpc.StatusCode.INVALID_ARGUMENT, "status code %s" % e.code()) + check(e.details() == "bad input %", "status message %r" % e.details()) + try: + ch.unary_unary("/test.Echo/Nope")(enc("x")) + check(False, "unimplemented") + except grpc.RpcError as e: + check(e.code() == grpc.StatusCode.UNIMPLEMENTED, "unimplemented %s" % e.code()) + check([dec(m) for m in count_(enc("4"))] == ["n0", "n1", "n2", "n3"], "server streaming") + got = [] + try: + for m in count_(enc("2")): + got.append(dec(m)) + check(False, "stream error") + except grpc.RpcError as e: + check(e.code() == grpc.StatusCode.ABORTED and got == ["n0", "n1"], "stream error") + check(dec(join_(iter([enc("a"), enc("b"), enc("c")]))) == "abc", "client streaming") + check([dec(m) for m in chat_(iter([enc("one"), enc("two")]))] == ["re:one", "re:two"], "bidi") + print("INTEROP OK", flush=True) + + +if __name__ == "__main__": + if sys.argv[1] == "server": + serve(int(sys.argv[2])) + else: + client(sys.argv[2]) diff --git a/vm/backend/impl/javase/com/codename1/backend/Http2.java b/vm/backend/impl/javase/com/codename1/backend/Http2.java index 635910175e0..8061a87c38b 100644 --- a/vm/backend/impl/javase/com/codename1/backend/Http2.java +++ b/vm/backend/impl/javase/com/codename1/backend/Http2.java @@ -22,50 +22,62 @@ */ package com.codename1.backend; +import com.codename1.backend.h2.H2Connection; + import java.io.IOException; -import java.nio.charset.StandardCharsets; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -/// HTTP/2 is deliberately absent from the local Java SE runtime. +/// HTTP/2 for the local Java SE runtime, on the pure-Java [H2Connection]. +/// +/// The packaged binary's twin is nghttp2; this one has the same public surface +/// so the shared server code needs no target-specific branch. The local runtime +/// does not terminate TLS, so it is reached only by h2c with prior knowledge -- +/// which is how gRPC talks over cleartext, and what the development loop needs +/// to serve and test gRPC services. /// -/// h2 is only ever reached through ALPN on a TLS connection, and the local runtime -/// does not terminate TLS (see Tls), so this could not be entered even if it were -/// implemented. Keeping the shape and refusing at create() means the shared server -/// code above needs no target-specific branch. +/// Header names and values are one char per octet, as the native side hands +/// them over. public final class Http2 { - /// The ALPN protocol identifier, needed by the shared code even here. + /// The ALPN protocol identifier, needed by the shared code. public static final String ALPN = "h2"; - private static final String UNSUPPORTED = - "HTTP/2 is not available in the local Java SE runtime -- it is reached " - + "through ALPN over TLS, which the local runtime does not terminate"; + private static volatile long maxBodyBytes = 64L * 1024 * 1024; //NOPMD AvoidUsingVolatile - set once at startup before any session exists, read by every session + + private final H2Connection connection = new H2Connection(true); private Http2() { + connection.setMaxBody(maxBodyBytes); } + /// @return a new server session + /// @throws IOException never on this arm; kept for the shared signature public static Http2 create() throws IOException { - throw new IOException(UNSUPPORTED); + return new Http2(); } - /// Mirrors the native runtime's stream shape so shared code compiles. + /// One request, as handed to the shared server. public static final class Stream { - final int id; - final String method; - final String path; - final String authority; - final Map headers; - final byte[] body; - private long bodyLength; - - Stream(int id, String method, String path, String authority, Map headers, byte[] body) { + private final int id; + private final String method; + private final String path; + private final String authority; + private final Map headers; + private final byte[] body; + private final boolean streaming; + + Stream(int id, String method, String path, String authority, Map headers, byte[] body, + boolean streaming) { this.id = id; this.method = method; this.path = path; this.authority = authority; this.headers = headers; this.body = body; - this.bodyLength = body == null ? 0 : body.length; + this.streaming = streaming; } public int getId() { @@ -88,116 +100,268 @@ public Map getHeaders() { return headers; } - /// The body as it ARRIVED, so the caller can check it before decoding. - /// Empty when the body was spooled; see [#takeBodyFd]. public byte[] getBody() { return body; } - /// The descriptor of a body that went to disk on arrival (an unlinked - /// temporary file), or -1 when it is in [#getBody]. Handed over once: - /// the caller owns closing it, and a second call answers -1. + /// Never spooled on this arm: bodies are bounded by the body limit and + /// held in memory. + /// + /// @return -1 public int takeBodyFd() { return -1; } - /// The body's whole length, wherever it is. public long getBodyLength() { - return bodyLength; + return body == null ? 0 : body.length; } public String getBodyAsString() { - if (body == null || body.length == 0) { + if (body == null) { return null; } - // A JDK always has UTF-8, so the old fallback to the platform default - // charset could not run -- but it named a charset nobody meant. - return new String(body, StandardCharsets.UTF_8); + try { + return new String(body, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return null; + } + } + + /// Whether this request was delivered at the end of its HEADERS, before + /// its body: true for a content type starting with `application/grpc`, + /// whose body then arrives through [Http2#takeData]. + /// + /// @return true for a streaming request + public boolean isStreaming() { + return streaming; } } public void receive(byte[] buffer, int offset, int length) throws IOException { - throw new IOException(UNSUPPORTED); + if (!connection.receive(buffer, offset, length) && connection.isDead()) { + throw new IOException("HTTP/2 framing error: " + connection.getDeathReason()); + } } public Stream nextRequest() { - return null; + H2Connection.Stream s = connection.nextReady(); + if (s == null) { + return null; + } + Map headers = new LinkedHashMap(); + String method = null; + String path = null; + String authority = null; + List h = s.headers; + for (int i = 0; i + 1 < h.size(); i += 2) { + String name = h.get(i); + String value = h.get(i + 1); + if (":method".equals(name)) { + method = value; + } else if (":path".equals(name)) { + path = value; + } else if (":authority".equals(name)) { + authority = value; + } else if (name.charAt(0) != ':') { + Object existing = headers.get(name); + if (existing == null) { + headers.put(name, value); + } else { + // Combined as the native twin combines them: cookies on "; ". + String separator = "cookie".equals(name) ? "; " : ","; + headers.put(name, String.valueOf(existing) + separator + value); + } + } + } + byte[] body = null; + if (!s.streaming) { + body = s.inbound.toByteArray(); + s.inbound.reset(); + } + return new Stream(s.id, method, path, authority, headers, body, s.streaming); } - /// As [#respond], with the body read from a descriptor rather than the heap. - /// Unsupported here for the same reason the rest of this class is: the local run - /// does not terminate TLS, so it never speaks HTTP/2. - public boolean respondFile(int streamId, int status, String contentType, List extraHeaders, - int fd, long offset, long length) throws IOException { - throw new IOException(UNSUPPORTED); + private static List responseHeaders(int status, String contentType, List extraHeaders) { + List out = new ArrayList(); + out.add(":status"); + out.add(String.valueOf(status)); + if (contentType != null) { + out.add("content-type"); + out.add(contentType); + } + addLines(out, extraHeaders); + return out; } - /// No session here, so there is no descriptor ceiling to enforce. - public static void setMaxFileBodies(int limit) { + private static void addLines(List out, List lines) { + if (lines == null) { + return; + } + for (Object entry : lines) { + String line = String.valueOf(entry); + int colon = line.indexOf(':'); + if (colon <= 0) { + continue; + } + String name = asciiLower(line.substring(0, colon).trim()); + String value = line.substring(colon + 1).trim(); + if (!"connection".equals(name) && !"transfer-encoding".equals(name) + && !"keep-alive".equals(name) && !"upgrade".equals(name)) { + out.add(name); + out.add(value); + } + } + } + + private static String asciiLower(String s) { + StringBuilder b = null; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c >= 'A' && c <= 'Z') { + if (b == null) { + b = new StringBuilder(s); + } + b.setCharAt(i, (char) (c + 32)); + } + } + return b == null ? s : b.toString(); } public boolean respond(int streamId, int status, String contentType, List extraHeaders, byte[] body) throws IOException { - throw new IOException(UNSUPPORTED); + boolean empty = body == null || body.length == 0; + connection.sendHeaders(streamId, responseHeaders(status, contentType, extraHeaders), empty); + if (!empty) { + connection.sendData(streamId, body, 0, body.length, true); + } + return true; + } + + /// As [#respond], with the body read from a descriptor. The descriptor is + /// owned from here and closed, as the native twin closes it. + public boolean respondFile(int streamId, int status, String contentType, List extraHeaders, + int fd, long offset, long length) throws IOException { + try { + if (length > Integer.MAX_VALUE - 16) { + throw new IOException("file too large for an HTTP/2 response here"); + } + byte[] data = new byte[(int) length]; + int done = 0; + while (done < data.length) { + int n = FileIo.pread(fd, data, done, data.length - done, offset + done); + if (n <= 0) { + throw new IOException("short read from a file response"); + } + done += n; + } + return respond(streamId, status, contentType, extraHeaders, data); + } finally { + FileIo.close(fd); + } + } + + /// No descriptor ceiling on this arm. + /// + /// @param limit ignored + public static void setMaxFileBodies(int limit) { + // Nothing to bound: files are read into memory and closed at once. } - /// Nothing is ever submitted here, so there is no ceiling to enforce. - /// Nothing to set: this arm does not serve HTTP/2. + /// @param limit the buffered body limit + /// @param spoolThreshold ignored: nothing is spooled here + /// @param dir ignored public static void setBodyLimits(long limit, int spoolThreshold, String dir) { + maxBodyBytes = limit; } + /// @param limit ignored: [#setBodyLimits] sets the one limit this arm has public static void setMaxBodyBytes(long limit) { + // The spool limit above is the effective one on this arm. } - /// Starts a response with one bounded chunk supplied at a time by the server. public boolean respondStream(int streamId, int status, String contentType, List headers) throws IOException { - throw new IOException(UNSUPPORTED); + connection.sendHeaders(streamId, responseHeaders(status, contentType, headers), false); + return true; } - /// Supplies the next chunk after the previous one has drained. public void streamChunk(int streamId, byte[] bytes, int length, boolean end) throws IOException { - throw new IOException(UNSUPPORTED); + if (length > 16384 || connection.pending(streamId) < 0) { + throw new IOException("HTTP/2 streamed response closed or not drained"); + } + connection.sendData(streamId, bytes, 0, length, end); + } + + /// Ends a stream started with [#respondStream] with trailers, after the data + /// already queued. + /// + /// @param streamId the stream + /// @param trailers `name: value` lines + /// @throws IOException when the stream is gone + public void streamEnd(int streamId, List trailers) throws IOException { + if (connection.pending(streamId) < 0) { + throw new IOException("HTTP/2 stream " + streamId + " is closed"); + } + List t = new ArrayList(); + addLines(t, trailers); + connection.sendTrailers(streamId, t); + } + + /// The request-body bytes of a streaming request received since the last + /// call, or null when none are buffered. Never blocks. + /// + /// @param streamId the stream + /// @return the bytes or null + public byte[] takeData(int streamId) { + return connection.takeData(streamId); + } + + /// 0 while the peer may still send, 1 once it ended its side (data may still + /// be buffered), -1 when the stream was reset or is gone. + /// + /// @param streamId the stream + /// @return the state + public int remoteState(int streamId) { + H2Connection.Stream s = connection.stream(streamId); + if (s == null || s.reset) { + return -1; + } + return s.remoteEnded ? 1 : 0; } - /// Aborts a failed response without terminating other streams in the session. public void resetStream(int streamId) throws IOException { - throw new IOException(UNSUPPORTED); + connection.reset(streamId); } - /// Unsent bytes, or -1 if the stream has closed or been reset. public int streamPending(int streamId) { - return -1; + return connection.pending(streamId); } public byte[] drain() throws IOException { - throw new IOException(UNSUPPORTED); + return connection.drain(); } public boolean isAlive() { - return false; + return !connection.isDead(); } - /// No session, so no stream ever closes. public int[] closedStreams() { - return null; + return connection.closedStreams(); } - /// Nothing is ever submitted here, so nothing is ever outstanding. public long pendingBodyBytes() { return 0; } - /// Likewise: no session, so no file-backed body holds a descriptor. public static int pendingBodyFiles() { return 0; } - /// And nothing is submitted, so no body holds heap either. public static long pendingBodyBytesAll() { return 0; } public void close() { + connection.shutdown(); } } diff --git a/vm/backend/impl/javase/com/codename1/backend/Web.java b/vm/backend/impl/javase/com/codename1/backend/Web.java index 05e1cc387c0..59000467bab 100644 --- a/vm/backend/impl/javase/com/codename1/backend/Web.java +++ b/vm/backend/impl/javase/com/codename1/backend/Web.java @@ -1013,6 +1013,28 @@ public void close() { } } + /// The status. HttpURLConnection cannot read a response while it is still + /// sending, so here this closes the request body first, as [#getStatus] + /// does; the translated twin keeps sending. The JavaSE gRPC client does + /// not use this class. + /// + /// @return the HTTP status + /// @throws IOException when the exchange failed + public int getStatusWhileSending() throws IOException { + return getStatus(); + } + + /// The response trailers: always empty here, since this runtime speaks + /// HTTP/1.1 and HttpURLConnection drops chunked trailers. See the + /// translated twin. + /// + /// @return an empty map + /// @throws IOException when the exchange has been closed + public Map getTrailers() throws IOException { + requireOpen(); + return new LinkedHashMap(); + } + private void awaitResponse() throws IOException { requireOpen(); if (status >= 0) { diff --git a/vm/backend/impl/javase/com/codename1/backend/h2/H2Connection.java b/vm/backend/impl/javase/com/codename1/backend/h2/H2Connection.java new file mode 100644 index 00000000000..e6394e56f64 --- /dev/null +++ b/vm/backend/impl/javase/com/codename1/backend/h2/H2Connection.java @@ -0,0 +1,1084 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.h2; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/// One HTTP/2 connection, RFC 9113, in either role, with no I/O of its own. +/// +/// Bytes from the socket go in through [#receive]; bytes for the socket come out +/// of [#drain]. Everything in between -- the preface, SETTINGS and their +/// acknowledgement, PING, HPACK, CONTINUATION, flow control in both directions, +/// RST_STREAM and GOAWAY -- is handled here, so the server twin (`Http2`) and the +/// client (`H2Client`) are both thin wrappers that only move bytes. +/// +/// Not thread safe. The server drives one from the connection's turn; the client +/// guards one with its own lock. +/// +/// What it refuses, because the native libraries refuse it and the dev loop must +/// not be kinder than production: +/// +/// - A frame larger than the SETTINGS_MAX_FRAME_SIZE we advertised (FRAME_SIZE_ERROR). +/// - A HEADERS block interrupted by any frame other than its CONTINUATION. +/// - A client stream id that is even, or not larger than the last one. +/// - Uppercase header names, connection-specific headers, pseudo-headers after +/// regular ones or in trailers, and a `te` other than `trailers` (a malformed +/// request is a stream error of type PROTOCOL_ERROR, 8.1.1). +/// - DATA beyond the window we granted (FLOW_CONTROL_ERROR), and a window update +/// that overflows 2^31-1. +public final class H2Connection { + public static final int DATA = 0; + public static final int HEADERS = 1; + public static final int PRIORITY = 2; + public static final int RST_STREAM = 3; + public static final int SETTINGS = 4; + public static final int PUSH_PROMISE = 5; + public static final int PING = 6; + public static final int GOAWAY = 7; + public static final int WINDOW_UPDATE = 8; + public static final int CONTINUATION = 9; + + static final int FLAG_END_STREAM = 0x1; + static final int FLAG_ACK = 0x1; + static final int FLAG_END_HEADERS = 0x4; + static final int FLAG_PADDED = 0x8; + static final int FLAG_PRIORITY = 0x20; + + public static final int NO_ERROR = 0; + public static final int PROTOCOL_ERROR = 1; + public static final int INTERNAL_ERROR = 2; + public static final int FLOW_CONTROL_ERROR = 3; + public static final int STREAM_CLOSED = 5; + public static final int FRAME_SIZE_ERROR = 6; + public static final int REFUSED_STREAM = 7; + public static final int CANCEL = 8; + public static final int COMPRESSION_ERROR = 9; + public static final int ENHANCE_YOUR_CALM = 11; + + static final byte[] PREFACE = { + 'P', 'R', 'I', ' ', '*', ' ', 'H', 'T', 'T', 'P', '/', '2', '.', '0', '\r', '\n', + '\r', '\n', 'S', 'M', '\r', '\n', '\r', '\n' + }; + + static final int DEFAULT_FRAME_SIZE = 16384; + static final int DEFAULT_WINDOW = 65535; + /// The window we grant every stream and the connection: large enough that a + /// gRPC message of the default 4 MB limit does not stall on round trips. + static final int LOCAL_WINDOW = 1 << 20; + static final int MAX_HEADER_LIST = 64 * 1024; + static final int MAX_CONCURRENT = 100; + + /// One stream as this connection sees it. Fields are read by the wrappers. + public static final class Stream { + public final int id; + /// The first header block: request headers on a server, response on a client. + public List headers; + /// The trailing header block, if the peer sent one. + public List trailers; + /// Data received and not yet taken by the application. + public final ByteArrayOutputStream inbound = new ByteArrayOutputStream(); + /// Total data received, for the body limit. + public long received; + public boolean remoteEnded; + public boolean localEnded; + /// The stream was reset by either side; nothing more flows. + public boolean reset; + public int resetCode; + /// Delivered to the application already (server: as a request). + boolean delivered; + boolean closedNoted; + /// Early delivery: data reaches the application through takeData and its + /// window is replenished only as it is taken. + public boolean streaming; + long sendWindow; + long recvWindow = LOCAL_WINDOW; + // Outbound data not yet framed, then optional trailers or end. + final ByteArrayOutputStream outbound = new ByteArrayOutputStream(); + int outboundOffset; + boolean endAfterData; + List trailersAfterData; + + Stream(int id, long sendWindow) { + this.id = id; + this.sendWindow = sendWindow; + } + + public int pendingOutbound() { + return outbound.size() - outboundOffset; + } + + public boolean isClosed() { + return reset || (remoteEnded && localEnded && pendingOutbound() == 0 + && trailersAfterData == null && !endAfterData); + } + } + + private final boolean server; + private final Hpack.Decoder decoder = new Hpack.Decoder(4096, MAX_HEADER_LIST); + private final Hpack.Encoder encoder = new Hpack.Encoder(); + private final ByteArrayOutputStream out = new ByteArrayOutputStream(); + private final Map streams = new HashMap(); + private final List ready = new ArrayList(); + private final List closed = new ArrayList(); + + private byte[] in = new byte[0]; + private int inLength; + private boolean prefaceSeen; + private int active; + private int lastPeerStream; + private int nextLocalStream; + private long connSendWindow = DEFAULT_WINDOW; + private long connRecvWindow = DEFAULT_WINDOW; + private int peerInitialWindow = DEFAULT_WINDOW; + private int peerMaxFrame = DEFAULT_FRAME_SIZE; + private int peerMaxConcurrent = Integer.MAX_VALUE; + private boolean dead; + private boolean goawayReceived; + private String deathReason; + private long maxBody = Long.MAX_VALUE; + + // A header block being assembled across CONTINUATION frames. + private int continuationStream; + private int continuationFlags; + private ByteArrayOutputStream continuation; + + /// @param server true for the server role, false for the client role + public H2Connection(boolean server) { + this.server = server; + this.nextLocalStream = server ? 2 : 1; + if (!server) { + out.write(PREFACE, 0, PREFACE.length); + } + // SETTINGS: ENABLE_PUSH=0, MAX_CONCURRENT_STREAMS, INITIAL_WINDOW_SIZE, + // MAX_HEADER_LIST_SIZE. Then grow the connection window to match. + byte[] settings = new byte[24]; + int p = 0; + p = setting(settings, p, 2, 0); + p = setting(settings, p, 3, MAX_CONCURRENT); + p = setting(settings, p, 4, LOCAL_WINDOW); + setting(settings, p, 6, MAX_HEADER_LIST); + frame(SETTINGS, 0, 0, settings, 0, settings.length); + windowUpdate(0, LOCAL_WINDOW - DEFAULT_WINDOW); + connRecvWindow = LOCAL_WINDOW; + } + + private static int setting(byte[] b, int p, int id, int value) { + b[p] = (byte) (id >>> 8); + b[p + 1] = (byte) id; + b[p + 2] = (byte) (value >>> 24); + b[p + 3] = (byte) (value >>> 16); + b[p + 4] = (byte) (value >>> 8); + b[p + 5] = (byte) value; + return p + 6; + } + + /// Bounds the body of a buffered (non-streaming) request or response. + /// + /// @param limit bytes; a stream over it is reset with CANCEL + public void setMaxBody(long limit) { + this.maxBody = limit; + } + + public boolean isDead() { + return dead; + } + + public String getDeathReason() { + return deathReason; + } + + public boolean isGoawayReceived() { + return goawayReceived; + } + + public Stream stream(int id) { + return streams.get(Integer.valueOf(id)); + } + + // =============================================================== output + + /// The bytes waiting for the socket, emptied by this call. + /// + /// @return the bytes, possibly empty + public byte[] drain() { + pump(); + byte[] b = out.toByteArray(); + out.reset(); + return b; + } + + public boolean hasOutput() { + pump(); + return out.size() > 0; + } + + private void frame(int type, int flags, int stream, byte[] payload, int off, int len) { + out.write(len >>> 16); + out.write(len >>> 8); + out.write(len); + out.write(type); + out.write(flags); + out.write((stream >>> 24) & 0x7f); + out.write(stream >>> 16); + out.write(stream >>> 8); + out.write(stream); + if (len > 0) { + out.write(payload, off, len); + } + } + + private void windowUpdate(int stream, int increment) { + if (increment <= 0) { + return; + } + byte[] b = {(byte) ((increment >>> 24) & 0x7f), (byte) (increment >>> 16), + (byte) (increment >>> 8), (byte) increment}; + frame(WINDOW_UPDATE, 0, stream, b, 0, 4); + } + + private void rst(Stream s, int code) { + if (s.reset) { + return; + } + s.reset = true; + s.resetCode = code; + byte[] b = {(byte) (code >>> 24), (byte) (code >>> 16), (byte) (code >>> 8), (byte) code}; + frame(RST_STREAM, 0, s.id, b, 0, 4); + noteClosed(s); + } + + private void goaway(int code, String reason) { + if (dead) { + return; + } + byte[] b = new byte[8]; + int last = lastPeerStream; + b[0] = (byte) ((last >>> 24) & 0x7f); + b[1] = (byte) (last >>> 16); + b[2] = (byte) (last >>> 8); + b[3] = (byte) last; + b[4] = (byte) (code >>> 24); + b[5] = (byte) (code >>> 16); + b[6] = (byte) (code >>> 8); + b[7] = (byte) code; + frame(GOAWAY, 0, 0, b, 0, 8); + dead = true; + deathReason = reason; + } + + /// Sends a GOAWAY with NO_ERROR. Streams already open finish; no new ones start. + public void shutdown() { + goaway(NO_ERROR, "shut down"); + } + + private void headerBlock(int stream, List headers, boolean endStream) { + byte[] block = encoder.encode(headers); + int pos = 0; + boolean first = true; + do { + int n = Math.min(peerMaxFrame, block.length - pos); + boolean last = pos + n == block.length; + int flags = (last ? FLAG_END_HEADERS : 0) | (first && endStream ? FLAG_END_STREAM : 0); + frame(first ? HEADERS : CONTINUATION, flags, stream, block, pos, n); + pos += n; + first = false; + } while (pos < block.length); + } + + /// Sends a header block. With `endStream` the stream's local side ends. + /// + /// @param id the stream + /// @param headers alternating lower-case names and values + /// @param endStream whether this ends our side + public void sendHeaders(int id, List headers, boolean endStream) { + Stream s = stream(id); + if (s == null || s.reset || s.localEnded || dead) { + return; + } + headerBlock(id, headers, endStream); + if (endStream) { + s.localEnded = true; + if (s.isClosed()) { + noteClosed(s); + } + } + } + + /// Queues data; it is framed as the windows allow, on [#drain]. + /// + /// @param id the stream + /// @param data the bytes + /// @param off offset + /// @param len length + /// @param endStream whether this ends our side once the data is sent + public void sendData(int id, byte[] data, int off, int len, boolean endStream) { + Stream s = stream(id); + if (s == null || s.reset || s.localEnded || s.endAfterData || s.trailersAfterData != null) { + return; + } + s.outbound.write(data, off, len); + if (endStream) { + s.endAfterData = true; + } + } + + /// Queues trailers after whatever data is queued; they end our side. + /// + /// @param id the stream + /// @param trailers alternating names and values, no pseudo-headers + public void sendTrailers(int id, List trailers) { + Stream s = stream(id); + if (s == null || s.reset || s.localEnded || s.endAfterData) { + return; + } + s.trailersAfterData = trailers; + } + + /// Resets a stream with CANCEL. + /// + /// @param id the stream + public void reset(int id) { + Stream s = stream(id); + if (s != null) { + rst(s, CANCEL); + } + } + + /// Bytes queued on a stream and not yet framed; -1 once it is reset or gone. + /// + /// @param id the stream + /// @return the count + public int pending(int id) { + Stream s = stream(id); + if (s == null || s.reset) { + return -1; + } + pump(); + return s.pendingOutbound(); + } + + private void pump() { + Iterator it = new ArrayList(streams.values()).iterator(); + while (it.hasNext()) { + Stream s = it.next(); + if (s.reset || s.closedNoted) { + continue; + } + while (s.pendingOutbound() > 0) { + long allowed = Math.min(Math.min(connSendWindow, s.sendWindow), peerMaxFrame); + if (allowed <= 0) { + break; + } + int n = (int) Math.min(allowed, s.pendingOutbound()); + byte[] buf = s.outbound.toByteArray(); + boolean last = n == s.pendingOutbound(); + boolean end = last && s.endAfterData; + frame(DATA, end ? FLAG_END_STREAM : 0, s.id, buf, s.outboundOffset, n); + s.outboundOffset += n; + connSendWindow -= n; + s.sendWindow -= n; + if (last) { + s.outbound.reset(); + s.outboundOffset = 0; + } + if (end) { + s.endAfterData = false; + s.localEnded = true; + } + } + if (s.pendingOutbound() == 0) { + if (s.endAfterData) { + // Zero-length end, or data that was all framed earlier. + frame(DATA, FLAG_END_STREAM, s.id, null, 0, 0); + s.endAfterData = false; + s.localEnded = true; + } + if (s.trailersAfterData != null) { + List t = s.trailersAfterData; + s.trailersAfterData = null; + headerBlock(s.id, t, true); + s.localEnded = true; + } + } + if (s.isClosed()) { + noteClosed(s); + } + } + } + + // A closed stream stays readable -- a client still has to read the trailers + // that closed it -- until the server reports it through closedStreams() or + // the client calls forget(). + private void noteClosed(Stream s) { + if (!s.closedNoted) { + s.closedNoted = true; + active--; + closed.add(Integer.valueOf(s.id)); + // A stream whose request was never taken must not be served later. + if (!s.delivered) { + ready.remove(s); + } + } + } + + /// Ids of streams that closed since the last call. + /// + /// @return the ids + public int[] closedStreams() { + int[] r = new int[closed.size()]; + for (int i = 0; i < r.length; i++) { + r[i] = closed.get(i).intValue(); + streams.remove(closed.get(i)); + } + closed.clear(); + return r; + } + + /// Drops a closed stream's state (client role, once its exchange is done). + /// + /// @param id the stream + public void forget(int id) { + Stream s = stream(id); + if (s != null && !s.closedNoted) { + rst(s, CANCEL); + } + streams.remove(Integer.valueOf(id)); + closed.remove(Integer.valueOf(id)); + } + + // =============================================================== client role + + /// Opens a stream (client role) with its request headers. + /// + /// @param headers alternating names and values, pseudo-headers first + /// @param endStream whether the request has no body + /// @return the stream id, or -1 when the connection cannot take another + public int open(List headers, boolean endStream) { + if (server || dead || goawayReceived || active >= peerMaxConcurrent) { + return -1; + } + int id = nextLocalStream; + nextLocalStream += 2; + Stream s = new Stream(id, peerInitialWindow); + s.streaming = true; + streams.put(Integer.valueOf(id), s); + active++; + headerBlock(id, headers, endStream); + s.localEnded = endStream; + return id; + } + + // =============================================================== server role + + /// The next request that is ready (server role): complete, or, for a + /// streaming request, its headers. Null when there is none. + /// + /// @return the stream + public Stream nextReady() { + while (!ready.isEmpty()) { + Stream s = ready.remove(0); + if (!s.reset) { + s.delivered = true; + return s; + } + } + return null; + } + + /// Takes a stream's buffered inbound data and replenishes the windows by as + /// much. For a server's streaming request and for every client stream. + /// + /// @param id the stream + /// @return the bytes, or null when none are buffered + public byte[] takeData(int id) { + Stream s = stream(id); + if (s == null || s.inbound.size() == 0) { + return null; + } + byte[] b = s.inbound.toByteArray(); + s.inbound.reset(); + if (!s.remoteEnded && !s.reset && s.streaming) { + s.recvWindow += b.length; + windowUpdate(id, b.length); + } + return b; + } + + // =============================================================== input + + /// Feeds bytes from the socket. + /// + /// @param data the bytes + /// @param off offset + /// @param len length + /// @return false when the connection died (a GOAWAY is queued; drain it, + /// then close the socket) + public boolean receive(byte[] data, int off, int len) { + if (dead && active == 0) { + return false; + } + if (inLength + len > in.length) { + byte[] grown = new byte[Math.max(in.length * 2, inLength + len)]; + System.arraycopy(in, 0, grown, 0, inLength); + in = grown; + } + System.arraycopy(data, off, in, inLength, len); + inLength += len; + int pos = 0; + try { + if (server && !prefaceSeen) { + int n = Math.min(inLength, PREFACE.length); + for (int i = 0; i < n; i++) { + if (in[i] != PREFACE[i]) { + throw new H2Error(PROTOCOL_ERROR, "bad connection preface"); + } + } + if (inLength < PREFACE.length) { + return true; + } + pos = PREFACE.length; + prefaceSeen = true; + } + while (inLength - pos >= 9) { + int length = ((in[pos] & 0xff) << 16) | ((in[pos + 1] & 0xff) << 8) | (in[pos + 2] & 0xff); + if (length > DEFAULT_FRAME_SIZE) { + throw new H2Error(FRAME_SIZE_ERROR, "frame of " + length + " octets"); + } + if (inLength - pos < 9 + length) { + break; + } + int type = in[pos + 3] & 0xff; + int flags = in[pos + 4] & 0xff; + int stream = ((in[pos + 5] & 0x7f) << 24) | ((in[pos + 6] & 0xff) << 16) + | ((in[pos + 7] & 0xff) << 8) | (in[pos + 8] & 0xff); + onFrame(type, flags, stream, in, pos + 9, length); + pos += 9 + length; + } + } catch (H2Error e) { + goaway(e.code, e.getMessage()); + inLength = 0; + return false; + } + System.arraycopy(in, pos, in, 0, inLength - pos); + inLength -= pos; + return !dead || active > 0; + } + + static final class H2Error extends Exception { + private static final long serialVersionUID = 1L; + final int code; + + H2Error(int code, String message) { + super(message); + this.code = code; + } + } + + private void onFrame(int type, int flags, int sid, byte[] b, int off, int len) throws H2Error { + if (continuation != null && (type != CONTINUATION || sid != continuationStream)) { + throw new H2Error(PROTOCOL_ERROR, "header block interrupted"); + } + switch (type) { + case DATA: + onData(flags, sid, b, off, len); + break; + case HEADERS: + onHeaders(flags, sid, b, off, len); + break; + case PRIORITY: + if (sid == 0) { + throw new H2Error(PROTOCOL_ERROR, "PRIORITY on stream 0"); + } + if (len != 5) { + Stream s = stream(sid); + if (s != null) { + rst(s, FRAME_SIZE_ERROR); + } + } + break; + case RST_STREAM: + onRst(sid, b, off, len); + break; + case SETTINGS: + onSettings(flags, sid, b, off, len); + break; + case PUSH_PROMISE: + throw new H2Error(PROTOCOL_ERROR, "PUSH_PROMISE with push disabled"); + case PING: + if (sid != 0) { + throw new H2Error(PROTOCOL_ERROR, "PING on a stream"); + } + if (len != 8) { + throw new H2Error(FRAME_SIZE_ERROR, "PING of " + len); + } + if ((flags & FLAG_ACK) == 0) { + frame(PING, FLAG_ACK, 0, b, off, 8); + } + break; + case GOAWAY: + if (sid != 0) { + throw new H2Error(PROTOCOL_ERROR, "GOAWAY on a stream"); + } + goawayReceived = true; + break; + case WINDOW_UPDATE: + onWindowUpdate(sid, b, off, len); + break; + case CONTINUATION: + if (continuation == null) { + throw new H2Error(PROTOCOL_ERROR, "CONTINUATION without HEADERS"); + } + continuation.write(b, off, len); + if (continuation.size() > MAX_HEADER_LIST * 2) { + throw new H2Error(ENHANCE_YOUR_CALM, "header block too large"); + } + if ((flags & FLAG_END_HEADERS) != 0) { + byte[] block = continuation.toByteArray(); + continuation = null; + headerBlockDone(continuationStream, continuationFlags, block, 0, block.length); + } + break; + default: + // Unknown frame types are ignored (5.5). + break; + } + } + + private void onSettings(int flags, int sid, byte[] b, int off, int len) throws H2Error { + if (sid != 0) { + throw new H2Error(PROTOCOL_ERROR, "SETTINGS on a stream"); + } + if ((flags & FLAG_ACK) != 0) { + if (len != 0) { + throw new H2Error(FRAME_SIZE_ERROR, "SETTINGS ack with a payload"); + } + return; + } + if (len % 6 != 0) { + throw new H2Error(FRAME_SIZE_ERROR, "SETTINGS of " + len); + } + for (int p = off; p < off + len; p += 6) { + int id = ((b[p] & 0xff) << 8) | (b[p + 1] & 0xff); + long value = ((long) (b[p + 2] & 0xff) << 24) | ((b[p + 3] & 0xff) << 16) + | ((b[p + 4] & 0xff) << 8) | (b[p + 5] & 0xff); + switch (id) { + case 1: + encoder.peerTableSizeChanged(); + break; + case 2: + if (value > 1 || (!server && value != 0)) { + throw new H2Error(PROTOCOL_ERROR, "bad ENABLE_PUSH"); + } + break; + case 3: + peerMaxConcurrent = (int) Math.min(value, Integer.MAX_VALUE); + break; + case 4: + if (value > 0x7fffffffL) { + throw new H2Error(FLOW_CONTROL_ERROR, "INITIAL_WINDOW_SIZE too large"); + } + long delta = value - peerInitialWindow; + peerInitialWindow = (int) value; + for (Stream s : streams.values()) { + s.sendWindow += delta; + if (s.sendWindow > 0x7fffffffL) { + throw new H2Error(FLOW_CONTROL_ERROR, "window overflow"); + } + } + break; + case 5: + if (value < DEFAULT_FRAME_SIZE || value > 16777215) { + throw new H2Error(PROTOCOL_ERROR, "bad MAX_FRAME_SIZE"); + } + peerMaxFrame = (int) value; + break; + default: + break; + } + } + frame(SETTINGS, FLAG_ACK, 0, null, 0, 0); + } + + private void onWindowUpdate(int sid, byte[] b, int off, int len) throws H2Error { + if (len != 4) { + throw new H2Error(FRAME_SIZE_ERROR, "WINDOW_UPDATE of " + len); + } + int inc = ((b[off] & 0x7f) << 24) | ((b[off + 1] & 0xff) << 16) + | ((b[off + 2] & 0xff) << 8) | (b[off + 3] & 0xff); + if (sid == 0) { + if (inc == 0) { + throw new H2Error(PROTOCOL_ERROR, "zero WINDOW_UPDATE"); + } + connSendWindow += inc; + if (connSendWindow > 0x7fffffffL) { + throw new H2Error(FLOW_CONTROL_ERROR, "connection window overflow"); + } + return; + } + Stream s = stream(sid); + if (s == null) { + return; + } + if (inc == 0) { + rst(s, PROTOCOL_ERROR); + return; + } + s.sendWindow += inc; + if (s.sendWindow > 0x7fffffffL) { + rst(s, FLOW_CONTROL_ERROR); + } + } + + private void onRst(int sid, byte[] b, int off, int len) throws H2Error { + if (sid == 0) { + throw new H2Error(PROTOCOL_ERROR, "RST_STREAM on stream 0"); + } + if (len != 4) { + throw new H2Error(FRAME_SIZE_ERROR, "RST_STREAM of " + len); + } + if (server && sid > lastPeerStream) { + throw new H2Error(PROTOCOL_ERROR, "RST_STREAM on an idle stream"); + } + Stream s = stream(sid); + if (s != null) { + s.reset = true; + s.resetCode = ((b[off] & 0xff) << 24) | ((b[off + 1] & 0xff) << 16) + | ((b[off + 2] & 0xff) << 8) | (b[off + 3] & 0xff); + noteClosed(s); + } + } + + private int unpad(int flags, byte[] b, int off, int len) throws H2Error { + if ((flags & FLAG_PADDED) == 0) { + return 0; + } + if (len < 1) { + throw new H2Error(PROTOCOL_ERROR, "padded frame without a pad length"); + } + int pad = b[off] & 0xff; + if (pad >= len) { + throw new H2Error(PROTOCOL_ERROR, "padding longer than the frame"); + } + return pad; + } + + private void onData(int flags, int sid, byte[] b, int off, int len) throws H2Error { + if (sid == 0) { + throw new H2Error(PROTOCOL_ERROR, "DATA on stream 0"); + } + // Flow control counts the whole frame, padding included. + connRecvWindow -= len; + if (connRecvWindow < 0) { + throw new H2Error(FLOW_CONTROL_ERROR, "connection window exceeded"); + } + // The connection window is replenished at once: per-stream windows are + // the backpressure, and a slow stream must not stall the others. + if (len > 0) { + connRecvWindow += len; + windowUpdate(0, len); + } + Stream s = stream(sid); + if (s == null) { + if (isIdle(sid)) { + throw new H2Error(PROTOCOL_ERROR, "DATA on an idle stream"); + } + // Closed: the frame still counted against the connection, and is dropped. + return; + } + if (s.reset || s.closedNoted) { + return; + } + if (s.remoteEnded || s.headers == null) { + rst(s, STREAM_CLOSED); + return; + } + s.recvWindow -= len; + if (s.recvWindow < 0) { + rst(s, FLOW_CONTROL_ERROR); + return; + } + int pad = unpad(flags, b, off, len); + int start = off + ((flags & FLAG_PADDED) != 0 ? 1 : 0); + int dataLen = len - pad - ((flags & FLAG_PADDED) != 0 ? 1 : 0); + s.inbound.write(b, start, dataLen); + s.received += dataLen; + if (!s.streaming) { + if (s.received > maxBody) { + rst(s, CANCEL); + return; + } + // Buffered whole: the limit is the backpressure, so grant it back now. + if (len > 0 && (flags & FLAG_END_STREAM) == 0) { + s.recvWindow += len; + windowUpdate(sid, len); + } + } else if (s.inbound.size() > maxStreamingBuffer()) { + rst(s, ENHANCE_YOUR_CALM); + return; + } else if (pad > 0 || (flags & FLAG_PADDED) != 0) { + // Padding is never "taken", so give its share of the window back here. + int padShare = len - dataLen; + s.recvWindow += padShare; + windowUpdate(sid, padShare); + } + if ((flags & FLAG_END_STREAM) != 0) { + remoteEnd(s); + } + } + + private static int maxStreamingBuffer() { + return LOCAL_WINDOW + 16 * 1024 * 1024; + } + + private boolean isIdle(int sid) { + boolean peerInitiated = server ? (sid & 1) == 1 : (sid & 1) == 0; + if (peerInitiated) { + return sid > lastPeerStream; + } + return sid >= nextLocalStream; + } + + private void remoteEnd(Stream s) { + s.remoteEnded = true; + if (server && !s.streaming && !s.delivered && !ready.contains(s)) { + ready.add(s); + } + if (s.isClosed()) { + noteClosed(s); + } + } + + private void onHeaders(int flags, int sid, byte[] b, int off, int len) throws H2Error { + if (sid == 0) { + throw new H2Error(PROTOCOL_ERROR, "HEADERS on stream 0"); + } + int pad = unpad(flags, b, off, len); + int start = off + ((flags & FLAG_PADDED) != 0 ? 1 : 0); + int end = off + len - pad; + if ((flags & FLAG_PRIORITY) != 0) { + start += 5; + } + if (start > end) { + throw new H2Error(FRAME_SIZE_ERROR, "HEADERS too short"); + } + if ((flags & FLAG_END_HEADERS) != 0) { + headerBlockDone(sid, flags, b, start, end - start); + } else { + continuation = new ByteArrayOutputStream(); + continuation.write(b, start, end - start); + continuationStream = sid; + continuationFlags = flags; + } + } + + private void headerBlockDone(int sid, int flags, byte[] block, int off, int len) throws H2Error { + List headers; + boolean tooLarge = false; + try { + headers = decoder.decode(block, off, len); + } catch (Hpack.CompressionException e) { + H2Error err = new H2Error(COMPRESSION_ERROR, e.getMessage()); + err.initCause(e); + throw err; + } catch (Hpack.HeaderListTooLargeException e) { + headers = null; + tooLarge = true; + } + boolean endStream = (flags & FLAG_END_STREAM) != 0; + Stream s = stream(sid); + if (s == null) { + if (!server) { + // A response for a stream we no longer track (reset by us): ignore. + if (isIdle(sid)) { + throw new H2Error(PROTOCOL_ERROR, "HEADERS on an idle stream"); + } + return; + } + if ((sid & 1) == 0) { + throw new H2Error(PROTOCOL_ERROR, "even client stream id"); + } + if (sid <= lastPeerStream) { + throw new H2Error(STREAM_CLOSED, "HEADERS on a closed stream"); + } + lastPeerStream = sid; + s = new Stream(sid, peerInitialWindow); + if (dead) { + // After our GOAWAY no new stream is processed. + return; + } + streams.put(Integer.valueOf(sid), s); + active++; + if (active > MAX_CONCURRENT) { + rst(s, REFUSED_STREAM); + return; + } + if (tooLarge) { + rst(s, ENHANCE_YOUR_CALM); + return; + } + String problem = validateRequest(headers); + if (problem != null) { + rst(s, PROTOCOL_ERROR); + return; + } + s.headers = headers; + s.streaming = isGrpc(headers); + if (s.streaming) { + ready.add(s); + } + if (endStream) { + remoteEnd(s); + } + return; + } + if (s.reset || s.closedNoted) { + return; + } + if (s.remoteEnded) { + rst(s, STREAM_CLOSED); + return; + } + if (tooLarge) { + rst(s, ENHANCE_YOUR_CALM); + return; + } + if (s.headers == null) { + // Client: the response headers. 1xx informational blocks are skipped. + String status = value(headers, ":status"); + if (status == null) { + rst(s, PROTOCOL_ERROR); + return; + } + if (status.length() == 3 && status.charAt(0) == '1') { + return; + } + s.headers = headers; + } else { + // Trailers: must end the stream and carry no pseudo-header. + if (!endStream) { + rst(s, PROTOCOL_ERROR); + return; + } + for (int i = 0; i < headers.size(); i += 2) { + if (headers.get(i).startsWith(":")) { + rst(s, PROTOCOL_ERROR); + return; + } + } + s.trailers = headers; + } + if (endStream) { + remoteEnd(s); + } + } + + private static boolean isGrpc(List headers) { + String type = value(headers, "content-type"); + return type != null && type.regionMatches(true, 0, "application/grpc", 0, 16); + } + + /// The value of the first header with that (lower-case) name, or null. + /// + /// @param headers alternating names and values + /// @param name the name + /// @return the value + public static String value(List headers, String name) { + if (headers == null) { + return null; + } + for (int i = 0; i + 1 < headers.size(); i += 2) { + if (headers.get(i).equals(name)) { + return headers.get(i + 1); + } + } + return null; + } + + static String validateRequest(List headers) { + boolean regularSeen = false; + String method = null; + String path = null; + String scheme = null; + for (int i = 0; i + 1 < headers.size(); i += 2) { + String name = headers.get(i); + String v = headers.get(i + 1); + if (name.length() == 0) { + return "empty header name"; + } + for (int k = 0; k < name.length(); k++) { + char c = name.charAt(k); + if (c >= 'A' && c <= 'Z') { + return "uppercase header name"; + } + } + if (name.charAt(0) == ':') { + if (regularSeen) { + return "pseudo-header after a regular header"; + } + if (":method".equals(name)) { + if (method != null) { + return "repeated :method"; + } + method = v; + } else if (":path".equals(name)) { + if (path != null) { + return "repeated :path"; + } + path = v; + } else if (":scheme".equals(name)) { + if (scheme != null) { + return "repeated :scheme"; + } + scheme = v; + } else if (!":authority".equals(name)) { + return "unknown pseudo-header"; + } + } else { + regularSeen = true; + if ("connection".equals(name) || "keep-alive".equals(name) + || "proxy-connection".equals(name) || "transfer-encoding".equals(name) + || "upgrade".equals(name)) { + return "connection-specific header"; + } + if ("te".equals(name) && !"trailers".equals(v)) { + return "te other than trailers"; + } + } + } + if (method == null) { + return "no :method"; + } + if ("CONNECT".equals(method)) { + return null; + } + if (scheme == null || path == null || path.length() == 0) { + return "missing :scheme or :path"; + } + return null; + } +} diff --git a/vm/backend/impl/javase/com/codename1/backend/h2/Hpack.java b/vm/backend/impl/javase/com/codename1/backend/h2/Hpack.java new file mode 100644 index 00000000000..5129f1aff7b --- /dev/null +++ b/vm/backend/impl/javase/com/codename1/backend/h2/Hpack.java @@ -0,0 +1,510 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.h2; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; + +/// HPACK, RFC 7541: the header compression of HTTP/2, for the Java SE runtime. +/// +/// The packaged binary uses nghttp2 and libcurl, which bring their own. This is +/// the dev-loop and test twin, so it is written to refuse everything the RFC +/// says a decoder must refuse, the way those libraries do, rather than to be +/// lenient: +/// +/// - An integer that overflows is a compression error, never a wrapped value. +/// - Huffman padding longer than seven bits, padding that is not all ones, or +/// an EOS symbol inside a string is a compression error (5.2). +/// - A dynamic table size update above the limit the decoder advertised is an +/// error, and one is only allowed at the start of a header block (4.2). +/// - The decoded header list is bounded (`SETTINGS_MAX_HEADER_LIST_SIZE`), counted +/// as the RFC counts it: name plus value plus 32 per field. +/// +/// Header names and values are carried as one char per octet (ISO-8859-1), +/// as the native HTTP/2 layer does, so a value round-trips byte for byte. +/// +/// The encoder never adds to its dynamic table. That is always valid and costs +/// some compression; for the dev loop correctness is what matters. +public final class Hpack { + /// The cost the RFC adds to every entry, for table and list size accounting. + static final int ENTRY_OVERHEAD = 32; + + static final String[][] STATIC_TABLE = { + {":authority", ""}, {":method", "GET"}, {":method", "POST"}, {":path", "/"}, + {":path", "/index.html"}, {":scheme", "http"}, {":scheme", "https"}, + {":status", "200"}, {":status", "204"}, {":status", "206"}, {":status", "304"}, + {":status", "400"}, {":status", "404"}, {":status", "500"}, + {"accept-charset", ""}, {"accept-encoding", "gzip, deflate"}, + {"accept-language", ""}, {"accept-ranges", ""}, {"accept", ""}, + {"access-control-allow-origin", ""}, {"age", ""}, {"allow", ""}, + {"authorization", ""}, {"cache-control", ""}, {"content-disposition", ""}, + {"content-encoding", ""}, {"content-language", ""}, {"content-length", ""}, + {"content-location", ""}, {"content-range", ""}, {"content-type", ""}, + {"cookie", ""}, {"date", ""}, {"etag", ""}, {"expect", ""}, {"expires", ""}, + {"from", ""}, {"host", ""}, {"if-match", ""}, {"if-modified-since", ""}, + {"if-none-match", ""}, {"if-range", ""}, {"if-unmodified-since", ""}, + {"last-modified", ""}, {"link", ""}, {"location", ""}, {"max-forwards", ""}, + {"proxy-authenticate", ""}, {"proxy-authorization", ""}, {"range", ""}, + {"referer", ""}, {"refresh", ""}, {"retry-after", ""}, {"server", ""}, + {"set-cookie", ""}, {"strict-transport-security", ""}, + {"transfer-encoding", ""}, {"user-agent", ""}, {"vary", ""}, {"via", ""}, + {"www-authenticate", ""} + }; + + private static final int[] CODES = { + 0x1ff8, 0x7fffd8, 0xfffffe2, 0xfffffe3, 0xfffffe4, 0xfffffe5, + 0xfffffe6, 0xfffffe7, 0xfffffe8, 0xffffea, 0x3ffffffc, 0xfffffe9, + 0xfffffea, 0x3ffffffd, 0xfffffeb, 0xfffffec, 0xfffffed, 0xfffffee, + 0xfffffef, 0xffffff0, 0xffffff1, 0xffffff2, 0x3ffffffe, 0xffffff3, + 0xffffff4, 0xffffff5, 0xffffff6, 0xffffff7, 0xffffff8, 0xffffff9, + 0xffffffa, 0xffffffb, 0x14, 0x3f8, 0x3f9, 0xffa, + 0x1ff9, 0x15, 0xf8, 0x7fa, 0x3fa, 0x3fb, + 0xf9, 0x7fb, 0xfa, 0x16, 0x17, 0x18, + 0x0, 0x1, 0x2, 0x19, 0x1a, 0x1b, + 0x1c, 0x1d, 0x1e, 0x1f, 0x5c, 0xfb, + 0x7ffc, 0x20, 0xffb, 0x3fc, 0x1ffa, 0x21, + 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, + 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, + 0x6f, 0x70, 0x71, 0x72, 0xfc, 0x73, + 0xfd, 0x1ffb, 0x7fff0, 0x1ffc, 0x3ffc, 0x22, + 0x7ffd, 0x3, 0x23, 0x4, 0x24, 0x5, + 0x25, 0x26, 0x27, 0x6, 0x74, 0x75, + 0x28, 0x29, 0x2a, 0x7, 0x2b, 0x76, + 0x2c, 0x8, 0x9, 0x2d, 0x77, 0x78, + 0x79, 0x7a, 0x7b, 0x7ffe, 0x7fc, 0x3ffd, + 0x1ffd, 0xffffffc, 0xfffe6, 0x3fffd2, 0xfffe7, 0xfffe8, + 0x3fffd3, 0x3fffd4, 0x3fffd5, 0x7fffd9, 0x3fffd6, 0x7fffda, + 0x7fffdb, 0x7fffdc, 0x7fffdd, 0x7fffde, 0xffffeb, 0x7fffdf, + 0xffffec, 0xffffed, 0x3fffd7, 0x7fffe0, 0xffffee, 0x7fffe1, + 0x7fffe2, 0x7fffe3, 0x7fffe4, 0x1fffdc, 0x3fffd8, 0x7fffe5, + 0x3fffd9, 0x7fffe6, 0x7fffe7, 0xffffef, 0x3fffda, 0x1fffdd, + 0xfffe9, 0x3fffdb, 0x3fffdc, 0x7fffe8, 0x7fffe9, 0x1fffde, + 0x7fffea, 0x3fffdd, 0x3fffde, 0xfffff0, 0x1fffdf, 0x3fffdf, + 0x7fffeb, 0x7fffec, 0x1fffe0, 0x1fffe1, 0x3fffe0, 0x1fffe2, + 0x7fffed, 0x3fffe1, 0x7fffee, 0x7fffef, 0xfffea, 0x3fffe2, + 0x3fffe3, 0x3fffe4, 0x7ffff0, 0x3fffe5, 0x3fffe6, 0x7ffff1, + 0x3ffffe0, 0x3ffffe1, 0xfffeb, 0x7fff1, 0x3fffe7, 0x7ffff2, + 0x3fffe8, 0x1ffffec, 0x3ffffe2, 0x3ffffe3, 0x3ffffe4, 0x7ffffde, + 0x7ffffdf, 0x3ffffe5, 0xfffff1, 0x1ffffed, 0x7fff2, 0x1fffe3, + 0x3ffffe6, 0x7ffffe0, 0x7ffffe1, 0x3ffffe7, 0x7ffffe2, 0xfffff2, + 0x1fffe4, 0x1fffe5, 0x3ffffe8, 0x3ffffe9, 0xffffffd, 0x7ffffe3, + 0x7ffffe4, 0x7ffffe5, 0xfffec, 0xfffff3, 0xfffed, 0x1fffe6, + 0x3fffe9, 0x1fffe7, 0x1fffe8, 0x7ffff3, 0x3fffea, 0x3fffeb, + 0x1ffffee, 0x1ffffef, 0xfffff4, 0xfffff5, 0x3ffffea, 0x7ffff4, + 0x3ffffeb, 0x7ffffe6, 0x3ffffec, 0x3ffffed, 0x7ffffe7, 0x7ffffe8, + 0x7ffffe9, 0x7ffffea, 0x7ffffeb, 0xffffffe, 0x7ffffec, 0x7ffffed, + 0x7ffffee, 0x7ffffef, 0x7fffff0, 0x3ffffee, 0x3fffffff, + }; + private static final byte[] LENGTHS = { + 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, + 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6, + 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, + 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6, + 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5, + 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, + 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23, + 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24, + 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, + 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23, + 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, + 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27, + 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, + 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, + 30, + }; + private static final int EOS = 256; + + /// The decode trie: node `n` has children `TRIE[2n]` (bit 0) and + /// `TRIE[2n+1]` (bit 1). A child below zero is a leaf holding `~symbol`; + /// zero means no such code. + private static final int[] TRIE; + + static { + int[] trie = new int[2 * 512]; + int next = 1; + for (int sym = 0; sym <= EOS; sym++) { + int code = CODES[sym]; + int len = LENGTHS[sym]; + int node = 0; + for (int bit = len - 1; bit > 0; bit--) { + int slot = 2 * node + ((code >>> bit) & 1); + if (trie[slot] == 0) { + trie[slot] = next++; + } + node = trie[slot]; + } + trie[2 * node + (code & 1)] = ~sym; + } + TRIE = trie; + } + + private Hpack() { + } + + /// A malformed header block. HTTP/2 answers it with a connection error of + /// type COMPRESSION_ERROR: the dynamic table can no longer be trusted. + public static final class CompressionException extends Exception { + private static final long serialVersionUID = 1L; + + CompressionException(String message) { + super(message); + } + } + + /// A header list too large for the advertised limit. Unlike a compression + /// error the table is intact, so this ends a stream, not the connection. + public static final class HeaderListTooLargeException extends Exception { + private static final long serialVersionUID = 1L; + + HeaderListTooLargeException(String message) { + super(message); + } + } + + // ---------------------------------------------------------------- integers + + static void writeInt(ByteArrayOutputStream out, int prefixBits, int flags, int value) { + int max = (1 << prefixBits) - 1; + if (value < max) { + out.write(flags | value); + return; + } + out.write(flags | max); + int rest = value - max; + while (rest >= 0x80) { + out.write((rest & 0x7f) | 0x80); + rest >>>= 7; + } + out.write(rest); + } + + /// Reads a prefixed integer at `pos[0]`, advancing it. + static int readInt(byte[] in, int[] pos, int end, int prefixBits) + throws CompressionException { + int max = (1 << prefixBits) - 1; + int value = in[pos[0]++] & max; + if (value < max) { + return value; + } + int shift = 0; + while (true) { + if (pos[0] >= end) { + throw new CompressionException("truncated integer"); + } + int b = in[pos[0]++] & 0xff; + if (shift > 28 || (shift == 28 && (b & 0x7f) > 7)) { + throw new CompressionException("integer overflow"); + } + value += (b & 0x7f) << shift; + if (value < 0) { + throw new CompressionException("integer overflow"); + } + if ((b & 0x80) == 0) { + return value; + } + shift += 7; + } + } + + // ----------------------------------------------------------------- huffman + + static int huffmanLength(String s) { + long bits = 0; + for (int i = 0; i < s.length(); i++) { + bits += LENGTHS[s.charAt(i) & 0xff]; + } + return (int) ((bits + 7) / 8); + } + + static void huffmanEncode(ByteArrayOutputStream out, String s) { + long acc = 0; + int bits = 0; + for (int i = 0; i < s.length(); i++) { + int sym = s.charAt(i) & 0xff; + acc = (acc << LENGTHS[sym]) | (CODES[sym] & 0xffffffffL); + bits += LENGTHS[sym]; + while (bits >= 8) { + bits -= 8; + out.write((int) (acc >>> bits)); + } + } + if (bits > 0) { + out.write((int) ((acc << (8 - bits)) | (0xff >>> bits))); + } + } + + static String huffmanDecode(byte[] in, int offset, int length) throws CompressionException { + StringBuilder out = new StringBuilder(length + length / 2); + int node = 0; + int depth = 0; + boolean allOnes = true; + for (int i = offset; i < offset + length; i++) { + int b = in[i] & 0xff; + for (int bit = 7; bit >= 0; bit--) { + int one = (b >>> bit) & 1; + int child = TRIE[2 * node + one]; + depth++; + allOnes &= one == 1; + if (child < 0) { + int sym = ~child; + if (sym == EOS) { + throw new CompressionException("EOS in huffman string"); + } + out.append((char) sym); + node = 0; + depth = 0; + allOnes = true; + } else if (child == 0) { + throw new CompressionException("invalid huffman code"); + } else { + node = child; + } + } + } + if (depth > 7 || !allOnes) { + throw new CompressionException("invalid huffman padding"); + } + return out.toString(); + } + + // ----------------------------------------------------------------- strings + + static void writeString(ByteArrayOutputStream out, String s) { + int h = huffmanLength(s); + if (h < s.length()) { + writeInt(out, 7, 0x80, h); + huffmanEncode(out, s); + } else { + writeInt(out, 7, 0, s.length()); + for (int i = 0; i < s.length(); i++) { + out.write(s.charAt(i) & 0xff); + } + } + } + + static String readString(byte[] in, int[] pos, int end) throws CompressionException { + if (pos[0] >= end) { + throw new CompressionException("truncated string"); + } + boolean huffman = (in[pos[0]] & 0x80) != 0; + int len = readInt(in, pos, end, 7); + if (len > end - pos[0]) { + throw new CompressionException("string past end of block"); + } + int start = pos[0]; + pos[0] += len; + if (huffman) { + return huffmanDecode(in, start, len); + } + StringBuilder s = new StringBuilder(len); + for (int i = start; i < start + len; i++) { + s.append((char) (in[i] & 0xff)); + } + return s.toString(); + } + + // ----------------------------------------------------------------- encoder + + /// Encodes header blocks. Stateless apart from a pending table size update, + /// because it never indexes; one per connection direction all the same. + public static final class Encoder { + private int pendingTableSize = -1; + + /// Called when the peer's SETTINGS_HEADER_TABLE_SIZE changes. Whatever the + /// new limit, the next block starts by setting our (always empty) table + /// to zero, which no limit the peer can advertise is below. + public void peerTableSizeChanged() { + pendingTableSize = 0; + } + + /// Encodes one header block. + /// + /// @param headers alternating names and values; names must be lower case + /// @return the block + public byte[] encode(List headers) { + ByteArrayOutputStream out = new ByteArrayOutputStream(64 + headers.size() * 16); + if (pendingTableSize >= 0) { + writeInt(out, 5, 0x20, pendingTableSize); + pendingTableSize = -1; + } + for (int i = 0; i + 1 < headers.size(); i += 2) { + String name = headers.get(i); + String value = headers.get(i + 1); + int nameIndex = 0; + int fullIndex = 0; + for (int s = 0; s < STATIC_TABLE.length; s++) { + if (STATIC_TABLE[s][0].equals(name)) { + if (nameIndex == 0) { + nameIndex = s + 1; + } + if (STATIC_TABLE[s][1].equals(value)) { + fullIndex = s + 1; + break; + } + } + } + if (fullIndex > 0) { + writeInt(out, 7, 0x80, fullIndex); + continue; + } + // Credentials are "never indexed" (6.2.3), so an intermediary + // that re-encodes the block does not put them in its table either. + boolean sensitive = "authorization".equals(name) || "cookie".equals(name) + || "proxy-authorization".equals(name); + int flags = sensitive ? 0x10 : 0x00; + writeInt(out, 4, flags, nameIndex); + if (nameIndex == 0) { + writeString(out, name); + } + writeString(out, value); + } + return out.toByteArray(); + } + } + + // ----------------------------------------------------------------- decoder + + /// Decodes header blocks and keeps the dynamic table between them. One per + /// connection direction; never shared. + public static final class Decoder { + private final int maxListSize; + private final int maxTableSize; + private int tableSize; + // The size the encoder last chose with a table size update; -1 until it does. + private int maxTableSizeInUse = -1; + // Newest entry first, as the RFC indexes it. + private final ArrayList table = new ArrayList(); + + /// @param maxTableSize the SETTINGS_HEADER_TABLE_SIZE we advertised + /// @param maxListSize the SETTINGS_MAX_HEADER_LIST_SIZE we advertised + public Decoder(int maxTableSize, int maxListSize) { + this.maxTableSize = maxTableSize; + this.maxListSize = maxListSize; + } + + int tableSize() { + return tableSize; + } + + /// Decodes one complete header block (HEADERS plus its CONTINUATIONs). + /// + /// The whole block is always decoded, even past the list limit, so the + /// dynamic table stays in step with the encoder's; only then is the + /// limit reported. + /// + /// @param block the bytes + /// @param offset where they start + /// @param length how many + /// @return alternating names and values + /// @throws CompressionException when the block is malformed + /// @throws HeaderListTooLargeException when it decodes past the limit + public List decode(byte[] block, int offset, int length) + throws CompressionException, HeaderListTooLargeException { + List out = new ArrayList(); + int[] pos = {offset}; + int end = offset + length; + long listSize = 0; + boolean fieldSeen = false; + while (pos[0] < end) { + int b = block[pos[0]] & 0xff; + if ((b & 0x80) != 0) { + int index = readInt(block, pos, end, 7); + String[] e = entry(index); + out.add(e[0]); + out.add(e[1]); + listSize += e[0].length() + e[1].length() + ENTRY_OVERHEAD; + fieldSeen = true; + } else if ((b & 0xe0) == 0x20) { + if (fieldSeen) { + throw new CompressionException("table size update after a field"); + } + int size = readInt(block, pos, end, 5); + if (size > maxTableSize) { + throw new CompressionException("table size update above the limit"); + } + evictTo(size); + maxTableSizeInUse = size; + } else { + boolean index = (b & 0xc0) == 0x40; + int nameIndex = readInt(block, pos, end, index ? 6 : 4); + String name = nameIndex == 0 ? readString(block, pos, end) : entry(nameIndex)[0]; + String value = readString(block, pos, end); + out.add(name); + out.add(value); + listSize += name.length() + value.length() + ENTRY_OVERHEAD; + fieldSeen = true; + if (index) { + add(name, value); + } + } + } + if (listSize > maxListSize) { + throw new HeaderListTooLargeException("header list of " + listSize + + " octets exceeds " + maxListSize); + } + return out; + } + + private int limit() { + return maxTableSizeInUse < 0 ? maxTableSize : maxTableSizeInUse; + } + + private String[] entry(int index) throws CompressionException { + if (index <= 0) { + throw new CompressionException("index 0"); + } + if (index <= STATIC_TABLE.length) { + return STATIC_TABLE[index - 1]; + } + int d = index - STATIC_TABLE.length - 1; + if (d >= table.size()) { + throw new CompressionException("index " + index + " past the table"); + } + return table.get(d); + } + + private void add(String name, String value) { + int size = name.length() + value.length() + ENTRY_OVERHEAD; + if (size > limit()) { + // Larger than the whole table: it empties the table and is not added (4.4). + table.clear(); + tableSize = 0; + return; + } + evictTo(limit() - size); + table.add(0, new String[] {name, value}); + tableSize += size; + } + + private void evictTo(int size) { + while (tableSize > size && !table.isEmpty()) { + String[] e = table.remove(table.size() - 1); + tableSize -= e[0].length() + e[1].length() + ENTRY_OVERHEAD; + } + } + } +} diff --git a/vm/backend/impl/javase/com/codename1/backend/h2/package-info.java b/vm/backend/impl/javase/com/codename1/backend/h2/package-info.java new file mode 100644 index 00000000000..4f62393312d --- /dev/null +++ b/vm/backend/impl/javase/com/codename1/backend/h2/package-info.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// HTTP/2 for the Java SE runtime in plain Java: HPACK and the frame layer, so +/// the development loop can serve and call gRPC, which needs trailers and full +/// duplex streams that neither the JDK's HTTP server nor its HTTP client offer. +/// The packaged binary uses nghttp2 and libcurl instead. +package com.codename1.backend.h2; diff --git a/vm/backend/impl/javase/com/codename1/impl/backend/GrpcCallTransport.java b/vm/backend/impl/javase/com/codename1/impl/backend/GrpcCallTransport.java new file mode 100644 index 00000000000..c689a77525b --- /dev/null +++ b/vm/backend/impl/javase/com/codename1/impl/backend/GrpcCallTransport.java @@ -0,0 +1,319 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl.backend; + +import com.codename1.backend.h2.H2Connection; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.URI; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +/// The HTTP/2 exchange under one outbound gRPC call, spoken here in pure Java +/// over a connection of its own: cleartext HTTP/2 with prior knowledge for +/// `http://`, TLS with ALPN `h2` for `https://`. The JDK's HTTP client drops +/// trailers, which is where gRPC puts its status, so it cannot be used. +/// +/// Single threaded: the caller's own thread reads the socket whenever it waits +/// for the peer, for headers, data or flow-control credit. +/// +/// Internal; `GrpcChannel` is the API. +public final class GrpcCallTransport { + private final Socket socket; + private boolean hasDeadline; + private long deadlineNanos; + private final InputStream in; + private final OutputStream out; + private final H2Connection h2 = new H2Connection(false); + private final byte[] buffer = new byte[16384]; + private final int id; + + private GrpcCallTransport(Socket socket, List headers) throws IOException { + this.socket = socket; + this.in = socket.getInputStream(); + this.out = socket.getOutputStream(); + int opened = h2.open(headers, false); + if (opened < 0) { + throw new IOException("could not open an HTTP/2 stream"); + } + this.id = opened; + flush(); + } + + /// Starts the call: connects and sends the request headers. + /// + /// @param url the full URL, `http://` (cleartext HTTP/2) or `https://` + /// @param headers "name: value" request headers + /// @param connectTimeoutMillis the connect timeout, 0 for none + /// @param deadlineMillis the call's deadline from now, negative for none; a read + /// that would wait past it fails instead of blocking + /// @return the call + /// @throws IOException when the connection fails + public static GrpcCallTransport open(String url, List headers, int connectTimeoutMillis, + long deadlineMillis) throws IOException { + URI uri = URI.create(url); + boolean tls = "https".equalsIgnoreCase(uri.getScheme()); + if (!tls && !"http".equalsIgnoreCase(uri.getScheme())) { + throw new IOException("a gRPC target is http:// or https://, not " + url); + } + String host = uri.getHost(); + int port = uri.getPort() > 0 ? uri.getPort() : tls ? 443 : 80; + Socket socket = new Socket(); //NOPMD CloseResource - kept open as this transport's connection, closed by close() or below on failure + boolean ok = false; + try { + socket.connect(new InetSocketAddress(host, port), Math.max(0, connectTimeoutMillis)); + socket.setTcpNoDelay(true); + if (tls) { + Socket wrapped = ((SSLSocketFactory) SSLSocketFactory.getDefault()) //NOPMD CloseResource - replaces the plain socket as the connection + .createSocket(socket, host, port, true); + if (!(wrapped instanceof SSLSocket)) { + wrapped.close(); + throw new IOException("the JDK's TLS socket factory made no SSLSocket"); + } + SSLSocket ssl = (SSLSocket) wrapped; //NOPMD CloseResource - the same connection under its TLS type + SSLParameters params = ssl.getSSLParameters(); + params.setApplicationProtocols(new String[] {"h2"}); + params.setEndpointIdentificationAlgorithm("HTTPS"); + ssl.setSSLParameters(params); + ssl.startHandshake(); + if (!"h2".equals(ssl.getApplicationProtocol())) { + throw new IOException(host + ":" + port + " did not agree to HTTP/2"); + } + socket = ssl; + } + String path = uri.getRawPath() == null || uri.getRawPath().length() == 0 + ? "/" : uri.getRawPath(); + List all = new ArrayList(); + all.add(":method"); + all.add("POST"); + all.add(":scheme"); + all.add(tls ? "https" : "http"); + all.add(":path"); + all.add(path); + all.add(":authority"); + all.add(uri.getPort() > 0 ? host + ":" + port : host); + for (String line : headers) { + int colon = line.indexOf(':'); + if (colon > 0) { + all.add(asciiLower(line.substring(0, colon).trim())); + all.add(line.substring(colon + 1).trim()); + } + } + GrpcCallTransport call = new GrpcCallTransport(socket, all); + if (deadlineMillis >= 0) { + call.hasDeadline = true; + call.deadlineNanos = System.nanoTime() + deadlineMillis * 1000000L; + } + ok = true; + return call; + } finally { + if (!ok) { + socket.close(); + } + } + } + + private static String asciiLower(String s) { + StringBuilder b = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + b.append(c >= 'A' && c <= 'Z' ? (char) (c + 32) : c); + } + return b.toString(); + } + + private void flush() throws IOException { + byte[] bytes = h2.drain(); + if (bytes.length > 0) { + out.write(bytes); + out.flush(); + } + } + + private void pump() throws IOException { + flush(); + if (h2.isDead()) { + throw new IOException("HTTP/2 connection failed: " + h2.getDeathReason()); + } + if (hasDeadline) { + // Rounded up, so the timeout never fires before the deadline has passed. + long remaining = (deadlineNanos - System.nanoTime() + 999999L) / 1000000L; + if (remaining <= 0) { + throw new java.net.SocketTimeoutException("gRPC deadline exceeded"); + } + socket.setSoTimeout((int) Math.min(Integer.MAX_VALUE, remaining)); + } + int n = in.read(buffer, 0, buffer.length); + if (n < 0) { + throw new IOException("HTTP/2 connection closed"); + } + if (!h2.receive(buffer, 0, n)) { + flush(); + throw new IOException("HTTP/2 connection failed: " + h2.getDeathReason()); + } + flush(); + } + + private H2Connection.Stream live() throws IOException { + H2Connection.Stream s = h2.stream(id); + if (s == null) { + throw new IOException("the HTTP/2 stream is gone"); + } + return s; + } + + /// Sends request bytes, waiting for flow-control credit. + /// + /// @param data the bytes + /// @throws IOException when the call failed + public void write(byte[] data) throws IOException { + h2.sendData(id, data, 0, data.length, false); + flush(); + for (;;) { + int pending = h2.pending(id); + if (pending < 0) { + throw new IOException("the gRPC stream was reset"); + } + if (pending == 0) { + return; + } + pump(); + } + } + + /// Ends the request side. + /// + /// @throws IOException when the call failed + public void endRequest() throws IOException { + H2Connection.Stream s = live(); + if (!s.localEnded) { + h2.sendData(id, new byte[0], 0, 0, true); + flush(); + } + } + + /// Waits for the response headers, without ending the request. + /// + /// @return the HTTP status + /// @throws IOException when the call failed + public int status() throws IOException { + String s = H2Connection.value(awaitHeaders(), ":status"); + try { + return s == null ? -1 : Integer.parseInt(s); + } catch (NumberFormatException e) { + return -1; + } + } + + private List awaitHeaders() throws IOException { + for (;;) { + H2Connection.Stream s = live(); + if (s.headers != null) { + return s.headers; + } + if (s.reset) { + throw new IOException("the gRPC stream was reset, HTTP/2 error " + s.resetCode); + } + pump(); + } + } + + /// @return the response headers, lower-case names to their first value + /// @throws IOException when the call failed + public Map headers() throws IOException { + return map(awaitHeaders()); + } + + /// The next response bytes, blocking. + /// + /// @return the bytes, or null at the end of the response + /// @throws IOException when the call failed + public byte[] read() throws IOException { + awaitHeaders(); + for (;;) { + byte[] data = h2.takeData(id); + if (data != null && data.length > 0) { + flush(); + return data; + } + H2Connection.Stream s = live(); + if (s.reset) { + throw new IOException("the gRPC stream was reset, HTTP/2 error " + s.resetCode); + } + if (s.remoteEnded) { + return null; + } + pump(); + } + } + + /// @return the trailers, once [#read] answered null + /// @throws IOException when the call failed + public Map trailers() throws IOException { + H2Connection.Stream s = live(); + if (s.trailers != null) { + return map(s.trailers); + } + // A trailers-only response carries its status in the headers block. + return s.headers == null ? new LinkedHashMap() : map(s.headers); + } + + /// Ends the call, cancelling it when it has not finished. + public void close() { + try { + H2Connection.Stream s = h2.stream(id); + if (s != null && !s.isClosed()) { + h2.reset(id); + } + h2.shutdown(); + flush(); + } catch (IOException ignored) { + // Closing anyway. + } finally { + try { + socket.close(); + } catch (IOException ignored) { + // Nothing more to do. + } + } + } + + private static Map map(List alt) { + Map out = new LinkedHashMap(); + for (int i = 0; i + 1 < alt.size(); i += 2) { + if (!out.containsKey(alt.get(i))) { + out.put(alt.get(i), alt.get(i + 1)); + } + } + return out; + } +} diff --git a/vm/backend/impl/parparvm/com/codename1/backend/Http2.java b/vm/backend/impl/parparvm/com/codename1/backend/Http2.java index db40500ed32..bdccdd5d11a 100644 --- a/vm/backend/impl/parparvm/com/codename1/backend/Http2.java +++ b/vm/backend/impl/parparvm/com/codename1/backend/Http2.java @@ -67,6 +67,7 @@ public static final class Stream { final byte[] body; private Http2 owner; private long bodyLength; + private boolean streaming; Stream(int id, String method, String path, String authority, Map headers, byte[] body) { this.id = id; @@ -78,6 +79,13 @@ public static final class Stream { this.bodyLength = body == null ? 0 : body.length; } + /// Whether this request was delivered at the end of its HEADERS, before its body: + /// true for content-type starting with "application/grpc" (ASCII case-insensitive), + /// whose body then arrives through takeData. + public boolean isStreaming() { + return streaming; + } + public int getId() { return id; } @@ -174,6 +182,10 @@ public Stream nextRequest() { } Stream stream = new Stream(id, methodImpl(session), pathImpl(session), authorityImpl(session), headers, bodyImpl(session)); + // Decided by the same rule the native applies (cn1H2IsGrpc), on the + // first content-type field; a repeated one was joined with "," above, which + // leaves the first value at the front. + stream.streaming = isGrpc(headers.get("content-type")); long length = bodyLengthImpl(session); if (length > stream.bodyLength) { // Spooled. The descriptor stays the session's -- freed with the @@ -285,6 +297,28 @@ public void streamChunk(int streamId, byte[] bytes, int length, boolean end) thr } } + /// Ends a stream started with respondStream by sending a trailing HEADERS frame + /// (END_STREAM) carrying these header lines ("name: value" strings, same encoding + /// rules as respond's extraHeaders), after every chunk already queued with + /// streamChunk has been sent. streamChunk(..., end=true) must not also be called. + public void streamEnd(int streamId, List trailers) throws IOException { + if (streamEndImpl(session, streamId, trailerBytes(trailers)) != 0) { + throw new IOException("HTTP/2 streamed response closed or trailers invalid"); + } + } + + /// The request-body bytes of a streaming request received since the last call, + /// or null when none are buffered. Never blocks. + public byte[] takeData(int streamId) { + return takeDataImpl(session, streamId); + } + + /// 0 = the peer may still send data, 1 = the peer ended its side (END_STREAM seen; + /// data may still be buffered for takeData), -1 = the stream was reset or is gone. + public int remoteState(int streamId) { + return remoteStateImpl(session, streamId); + } + /// Aborts a failed response without terminating other streams in the session. public void resetStream(int streamId) throws IOException { if (resetStreamImpl(session, streamId) != 0) { @@ -430,6 +464,38 @@ private static native int respondFileImpl(long session, int streamId, String sta private static native int streamChunkImpl(long session, int streamId, byte[] bytes, int length, boolean end); private static native int resetStreamImpl(long session, int streamId); private static native int streamPendingImpl(long session, int streamId); + private static native int streamEndImpl(long session, int streamId, byte[] trailers); + private static native byte[] takeDataImpl(long session, int streamId); + private static native int remoteStateImpl(long session, int streamId); + + /// The trailer block: headerBytes' encoding without a content-type line. + private static byte[] trailerBytes(List trailers) { + StringBuilder joined = new StringBuilder(); + if (trailers != null) { + for (Object header : trailers) { + if (joined.length() > 0) { + joined.append('\n'); + } + joined.append(String.valueOf(header)); + } + } + return HeaderLines.narrowed(joined.toString()); + } + + /// "application/grpc" as a prefix, ASCII case folded by hand: toLowerCase is + /// locale sensitive and there is no root locale to ask for. + /// + /// Must agree with the native `cn1H2IsGrpc`, which already routed the stream's + /// DATA to the streaming path: both test the same prefix on the first + /// content-type value (a joined repeat still starts with it). + static boolean isGrpc(Object contentType) { + if (!(contentType instanceof String)) { + return false; + } + String value = (String) contentType; + String prefix = "application/grpc"; + return value.length() >= prefix.length() && value.regionMatches(true, 0, prefix, 0, prefix.length()); + } private static native int respondImpl(long session, int streamId, String status, byte[] headerLines, byte[] body); diff --git a/vm/backend/impl/parparvm/com/codename1/backend/Web.java b/vm/backend/impl/parparvm/com/codename1/backend/Web.java index d04275c07ef..e7268d9c880 100644 --- a/vm/backend/impl/parparvm/com/codename1/backend/Web.java +++ b/vm/backend/impl/parparvm/com/codename1/backend/Web.java @@ -635,12 +635,41 @@ public void close() { } } + /// The status, read WITHOUT closing the request body: for a full-duplex + /// exchange (a bidirectional gRPC call) whose server answers before the + /// request ends. [#getStatus] closes the request body first. + /// + /// @return the HTTP status + /// @throws IOException when the exchange failed + public int getStatusWhileSending() throws IOException { + awaitResponse(false); + return status; + } + + /// The response trailers, once [#getResponseBody] has been read to its + /// end: the header fields that followed the body (HTTP/2 trailers, which is + /// where gRPC puts its status). Empty when there were none. + /// + /// @return lower-case names to every value, in arrival order + /// @throws IOException when the body has not been read to its end + public Map getTrailers() throws IOException { + requireOpen(); + if (!ended) { + throw new IOException("the trailers follow the body; read it to its end first"); + } + return parseHeaders(trailerText(headersImpl(handle))); + } + private void awaitResponse() throws IOException { + awaitResponse(true); + } + + private void awaitResponse(boolean closeRequest) throws IOException { requireOpen(); if (headersRead) { return; } - if (!requestDone) { + if (!requestDone && closeRequest) { getRequestBody().close(); } int state = streamStepImpl(handle, WANT_HEADERS); @@ -734,6 +763,32 @@ private static String protocolName(int version) { } } + /// What libcurl appended to the header buffer after the final response's + /// header block: the trailers. 1xx blocks come first, each opened by its own + /// status line, so the block that matters is the one after the last one. + static String trailerText(String raw) { + if (raw == null) { + return null; + } + int status = raw.startsWith("HTTP/") ? 0 : -1; + int at = raw.indexOf("\nHTTP/"); + while (at >= 0) { + status = at + 1; + at = raw.indexOf("\nHTTP/", at + 1); + } + if (status < 0) { + return null; + } + int blank = raw.indexOf("\r\n\r\n", status); + int skip = 4; + int bare = raw.indexOf("\n\n", status); + if (blank < 0 || (bare >= 0 && bare < blank)) { + blank = bare; + skip = 2; + } + return blank < 0 ? null : raw.substring(blank + skip); + } + /// libcurl hands back the raw header block, status lines and all. Redirects /// mean there can be several blocks; the LAST one describes the response the /// caller got, so a later block replaces an earlier one rather than merging diff --git a/vm/backend/impl/parparvm/com/codename1/impl/backend/GrpcCallTransport.java b/vm/backend/impl/parparvm/com/codename1/impl/backend/GrpcCallTransport.java new file mode 100644 index 00000000000..ae265c85d60 --- /dev/null +++ b/vm/backend/impl/parparvm/com/codename1/impl/backend/GrpcCallTransport.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl.backend; + +import com.codename1.backend.Web; +import com.codename1.backend.WebClient; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// The HTTP/2 exchange under one outbound gRPC call: libcurl through a +/// full-duplex `Web.Exchange`. The JavaSE twin speaks HTTP/2 itself. +/// +/// Internal; `GrpcChannel` is the API. +public final class GrpcCallTransport { + private final WebClient client; + private final Web.Exchange exchange; + private boolean hasDeadline; + private long deadlineNanos; + private OutputStream body; + private InputStream in; + private final byte[] buffer = new byte[16384]; + private boolean requestEnded; + + private GrpcCallTransport(WebClient client, Web.Exchange exchange) { + this.client = client; + this.exchange = exchange; + } + + /// Starts the call: sends the request headers. + /// + /// @param url the full URL, `http://` (cleartext HTTP/2) or `https://` + /// @param headers "name: value" request headers + /// @param connectTimeoutMillis the connect timeout, 0 for the default + /// @param deadlineMillis the call's deadline from now, negative for none; a read + /// that would wait past it fails instead of blocking + /// @return the call + /// @throws IOException when the connection fails + public static GrpcCallTransport open(String url, List headers, int connectTimeoutMillis, + long deadlineMillis) throws IOException { + WebClient client = new WebClient().setRequireHttp2(true); + if (connectTimeoutMillis > 0) { + client.setConnectTimeoutMillis(connectTimeoutMillis); + } + // A stream ignores the request timeout. With a deadline, the read timeout + // bounds a peer that stalls past it, and read() checks the deadline itself + // so one that trickles bytes is stopped too. Without one, a quiet stream + // (a watch, a subscription) may wait as long as it likes, as gRPC allows. + client.setReadTimeoutMillis(deadlineMillis >= 0 + ? (int) Math.max(1, Math.min(Integer.MAX_VALUE, deadlineMillis)) : 0); + boolean ok = false; + try { + Web.Exchange exchange = client.open("POST", url, headers, -1); + ok = true; + GrpcCallTransport call = new GrpcCallTransport(client, exchange); + if (deadlineMillis >= 0) { + call.hasDeadline = true; + call.deadlineNanos = System.nanoTime() + deadlineMillis * 1000000L; + } + return call; + } finally { + if (!ok) { + client.close(); + } + } + } + + /// Sends request bytes. + /// + /// @param data the bytes + /// @throws IOException when the call failed + public void write(byte[] data) throws IOException { + if (body == null) { + body = exchange.getRequestBody(); + } + body.write(data, 0, data.length); + } + + /// Ends the request side. + /// + /// @throws IOException when the call failed + public void endRequest() throws IOException { + if (requestEnded) { + return; + } + requestEnded = true; + if (body == null) { + body = exchange.getRequestBody(); + } + body.close(); + } + + /// Waits for the response headers, without ending the request. + /// + /// @return the HTTP status + /// @throws IOException when the call failed + public int status() throws IOException { + return exchange.getStatusWhileSending(); + } + + /// @return the response headers, lower-case names to their first value + /// @throws IOException when the call failed + public Map headers() throws IOException { + exchange.getStatusWhileSending(); + return first(exchange.getHeaderValueMap()); + } + + /// The next response bytes, blocking. + /// + /// @return the bytes, or null at the end of the response + /// @throws IOException when the call failed + public byte[] read() throws IOException { + exchange.getStatusWhileSending(); + if (in == null) { + in = exchange.getResponseBody(); + } + checkDeadline(); + int n = in.read(buffer, 0, buffer.length); + checkDeadline(); + if (n < 0) { + return null; + } + byte[] out = new byte[n]; + System.arraycopy(buffer, 0, out, 0, n); + return out; + } + + /// @return the trailers, once [#read] answered null + /// @throws IOException when the call failed + public Map trailers() throws IOException { + return first(exchange.getTrailers()); + } + + private void checkDeadline() throws IOException { + if (hasDeadline && System.nanoTime() - deadlineNanos >= 0) { + close(); + throw new IOException("gRPC deadline exceeded"); + } + } + + /// Ends the call, cancelling it when it has not finished. + public void close() { + exchange.close(); + client.close(); + } + + private static Map first(Map all) { + Map out = new LinkedHashMap(); + for (Object k : all.keySet()) { + Object v = all.get(k); + if (v instanceof List && !((List) v).isEmpty()) { + out.put(String.valueOf(k), String.valueOf(((List) v).get(0))); + } + } + return out; + } +} diff --git a/vm/backend/native/cn1_backend_http2.c b/vm/backend/native/cn1_backend_http2.c index 33662b7e271..97f502ffdb4 100644 --- a/vm/backend/native/cn1_backend_http2.c +++ b/vm/backend/native/cn1_backend_http2.c @@ -110,9 +110,39 @@ typedef struct CN1H2Request { /* The largest body this stream may carry, decided from its headers on its first DATA chunk (0 until then); see cn1H2BodyCap. */ long bodyCap; + /* Delivered at the end of its HEADERS (gRPC), so `body` stays empty and the + DATA that follows goes to the stream's CN1H2Inbound instead. */ + int streaming; struct CN1H2Request* next; } CN1H2Request; +/* + * The request body of a STREAMING request (gRPC), received while the handler runs. + * + * Not a field of CN1H2Request, because that request leaves every list Java can + * reach the moment it is delivered: nextRequest frees it as soon as Java moves + * on to the next one, which for a bidirectional call is long before the client + * has finished sending. This lives on the session from the end of the HEADERS + * until the stream closes, and takeData empties it. Its memory is charged to the + * same process-wide inbound total as any other request body, at its capacity. + */ +typedef struct CN1H2Inbound { + int32_t streamId; + unsigned char* data; + size_t length; + size_t capacity; + /* remoteState: 0 open, 1 the peer sent END_STREAM, -1 reset. */ + int state; + struct CN1H2Inbound* next; +} CN1H2Inbound; + +/* How much of a streaming body may wait for takeData. One maximum gRPC message + (4 MiB default, 8 MiB is the budget the plain body path already allows) plus + its 5-byte frame prefix: a client that sends more than one full message ahead + of a handler that is not reading is resetting itself, not being throttled -- + flow control is nghttp2's automatic window, which does not wait on Java. */ +#define CN1_H2_MAX_STREAMING_BYTES (CN1_H2_MAX_BODY_BYTES + 5) + /* * One response body, owned by the stream that is sending it. * @@ -136,6 +166,12 @@ typedef struct CN1H2Body { size_t offset; int streaming; int finished; + /* streamEnd's trailer section: the "name: value" block (owned, terminated) + and the nghttp2_nv entries pointing into it, submitted from the read + callback at EOF. NULL when the stream ends with its last DATA frame. */ + char* trailerBlock; + nghttp2_nv* trailerNva; + size_t trailerCount; struct CN1H2Body* next; } CN1H2Body; @@ -165,6 +201,8 @@ typedef struct { NO_ERROR closes with error code 0 -- exactly like a response sent in full. This is how the close tells the two apart. */ int32_t resetStream; + /* Streaming request bodies, one per stream; see CN1H2Inbound. */ + CN1H2Inbound* inbound; } CN1H2Session; /* @@ -315,6 +353,8 @@ static void cn1H2FreeBody(CN1H2Body* body) { close(body->fd); } free(body->data); + free(body->trailerBlock); + free(body->trailerNva); free(body); } @@ -389,6 +429,118 @@ static void cn1H2Unlink(CN1H2Request** list, CN1H2Request* target) { } } +static CN1H2Inbound* cn1H2FindInbound(CN1H2Session* s, int32_t streamId) { + CN1H2Inbound* in; + if(s == NULL) { + return NULL; + } + for(in = s->inbound; in != NULL; in = in->next) { + if(in->streamId == streamId) { + return in; + } + } + return NULL; +} + +/* Frees a streaming buffer's bytes and returns their charge. The entry itself + stays (state still answers remoteState) until cn1H2FreeInbound. */ +static void cn1H2DropInboundData(CN1H2Inbound* in) { + if(in->capacity > 0) { + cn1H2ReleaseInboundBytes((long)in->capacity); + } + free(in->data); + in->data = NULL; + in->length = 0; + in->capacity = 0; +} + +static void cn1H2FreeInbound(CN1H2Session* s, int32_t streamId) { + CN1H2Inbound** link = &s->inbound; + while(*link != NULL) { + if((*link)->streamId == streamId) { + CN1H2Inbound* gone = *link; + *link = gone->next; + cn1H2DropInboundData(gone); + free(gone); + return; + } + link = &(*link)->next; + } +} + +/* Whether a request is gRPC: content-type "application/grpc" followed by + nothing, "+proto"-style suffixes or parameters -- a prefix match, ASCII case + folded by hand (see the CLAUDE.md note on toLowerCase; the same holds here). */ +static int cn1H2IsGrpc(CN1H2Request* r) { + static const char prefix[] = "application/grpc"; + int i; + for(i = 0 ; i < r->headerCount ; i++) { + if(strcmp(r->headers[i].name, "content-type") == 0) { + const char* v = r->headers[i].value; + size_t k; + for(k = 0 ; k < sizeof(prefix) - 1 ; k++) { + char c = v[k]; + if(c >= 'A' && c <= 'Z') { + c = (char)(c - 'A' + 'a'); + } + if(c != prefix[k]) { + return 0; /* also stops at the terminator of a short value */ + } + } + return 1; + } + } + return 0; +} + +/* Appends one DATA chunk of a streaming request. Over the bound, or out of + memory, the stream is reset and remoteState answers -1 from then on: a handler + reading a message that silently lost its middle would decode garbage. */ +static void cn1H2AppendInbound(CN1H2Session* s, CN1H2Inbound* in, + const uint8_t* data, size_t length) { + if(in->state < 0 || length == 0) { + return; + } + if(in->length + length > CN1_H2_MAX_STREAMING_BYTES) { + in->state = -1; + cn1H2DropInboundData(in); + nghttp2_submit_rst_stream(s->session, NGHTTP2_FLAG_NONE, in->streamId, + NGHTTP2_ENHANCE_YOUR_CALM); + return; + } + if(in->length + length > in->capacity) { + size_t grown = in->capacity == 0 ? 16384 : in->capacity * 2; + unsigned char* bigger; + while(grown < in->length + length) { + grown *= 2; + } + if(grown > CN1_H2_MAX_STREAMING_BYTES) { + grown = CN1_H2_MAX_STREAMING_BYTES; + } + /* Charged before the allocation, given back if it fails -- the order + cn1H2ReserveInboundBytes explains. */ + if(!cn1H2ReserveInboundBytes((long)(grown - in->capacity))) { + bigger = NULL; + } else { + bigger = (unsigned char*)realloc(in->data, grown); + if(bigger == NULL) { + cn1H2ReleaseInboundBytes((long)(grown - in->capacity)); + } + } + if(bigger == NULL) { + in->state = -1; + cn1H2DropInboundData(in); + nghttp2_submit_rst_stream(s->session, NGHTTP2_FLAG_NONE, in->streamId, + NGHTTP2_ENHANCE_YOUR_CALM); + return; + } + in->data = bigger; + in->capacity = grown; + } + memcpy(in->data + in->length, data, length); + in->length += length; +} + static void cn1H2Enqueue(CN1H2Session* s, CN1H2Request* r) { r->next = NULL; if(s->readyTail == NULL) { @@ -668,8 +820,16 @@ static void cn1H2RefuseTooLarge(CN1H2Session* s, CN1H2Request* r); static int cn1H2OnData(nghttp2_session* session, uint8_t flags, int32_t streamId, const uint8_t* data, size_t length, void* userData) { CN1H2Session* s = (CN1H2Session*)userData; - CN1H2Request* open = cn1H2FindOpen(s, streamId); + CN1H2Request* open; int result; + CN1H2Inbound* in = cn1H2FindInbound(s, streamId); + if(in != NULL) { + /* Never the body cap, the 413 or the spool: none of them fit a body that + is consumed while it arrives. CN1_H2_MAX_STREAMING_BYTES bounds it. */ + cn1H2AppendInbound(s, in, data, length); + return 0; + } + open = cn1H2FindOpen(s, streamId); /* Too large is answered, as HTTP/1 answers it: a 413 the client can read, then RST_STREAM(NO_ERROR) so it stops sending (RFC 9113 8.1). Only a plain reset used to follow, which an uploader reports as a protocol @@ -1085,10 +1245,47 @@ static int cn1H2OnFrameRecv(nghttp2_session* session, const nghttp2_frame* frame if(frame->hd.type != NGHTTP2_HEADERS && frame->hd.type != NGHTTP2_DATA) { return 0; } + { + /* A streaming request was delivered already; all that is left to learn + is that the peer finished -- on its last DATA frame or a trailer + HEADERS, whose fields are dropped as on_header drops every trailer. */ + CN1H2Inbound* in = cn1H2FindInbound(s, frame->hd.stream_id); + if(in != NULL) { + if(endStream && in->state == 0) { + in->state = 1; + } + return 0; + } + } r = cn1H2FindOpen(s, frame->hd.stream_id); if(r == NULL || r->refused) { return 0; /* a refused stream is freed when its reset closes it */ } + if(frame->hd.type == NGHTTP2_HEADERS + && frame->headers.cat == NGHTTP2_HCAT_REQUEST + && cn1H2IsGrpc(r)) { + /* gRPC: delivered at the end of its HEADERS, because a streaming call + needs its handler running before the client stops sending -- waiting + for END_STREAM would deadlock every bidirectional call. Expect is not + resolved: gRPC clients do not send it. END_STREAM may already be on + this frame (a call with no request message), hence the initial state. */ + CN1H2Inbound* in = (CN1H2Inbound*)calloc(1, sizeof(CN1H2Inbound)); + if(in == NULL) { + r->refused = 1; + nghttp2_submit_rst_stream(s->session, NGHTTP2_FLAG_NONE, r->streamId, + NGHTTP2_INTERNAL_ERROR); + return 0; + } + in->streamId = r->streamId; + in->state = endStream ? 1 : 0; + in->next = s->inbound; + s->inbound = in; + cn1H2Unlink(&s->open, r); + r->complete = 1; + r->streaming = 1; + cn1H2Enqueue(s, r); + return 0; + } /* BEFORE the END_STREAM test below, because a request that is waiting to be told to send its body has not set it. */ if(frame->hd.type == NGHTTP2_HEADERS @@ -1170,6 +1367,9 @@ static int cn1H2OnStreamClose(nghttp2_session* session, int32_t streamId, or the body limit above reset it -- would otherwise sit on the list until the session ends. */ cn1H2ReleaseBodyForStream(s, streamId); + /* Closed means both sides are done or it was reset; either way no handler + can still need what it had not taken, and remoteState answers -1. */ + cn1H2FreeInbound(s, streamId); return 0; } @@ -1508,8 +1708,6 @@ static ssize_t cn1H2ReadBody(nghttp2_session* session, int32_t streamId, uint8_t CN1H2Session* s = (CN1H2Session*)userData; CN1H2Body* body = (CN1H2Body*)source->ptr; size_t remaining; - (void)session; - (void)streamId; if(body == NULL) { *dataFlags |= NGHTTP2_DATA_FLAG_EOF; return 0; @@ -1562,6 +1760,21 @@ static ssize_t cn1H2ReadBody(nghttp2_session* session, int32_t streamId, uint8_t } if(body->offset >= body->length && (!body->streaming || body->finished)) { *dataFlags |= NGHTTP2_DATA_FLAG_EOF; + if(body->trailerNva != NULL) { + /* The documented way to end with trailers: EOF without END_STREAM on + this DATA frame, and nghttp2_submit_trailer from inside the read + callback, which queues the HEADERS(END_STREAM) right behind it. + nghttp2 copies the fields during the submit, so the body (which + owns them) can go immediately after. If the submit fails the + stream is reset instead: closing it without the grpc-status the + client waits for would leave it hanging on a half-closed call. */ + *dataFlags |= NGHTTP2_DATA_FLAG_NO_END_STREAM; + if(nghttp2_submit_trailer(session, streamId, body->trailerNva, + body->trailerCount) != 0) { + nghttp2_submit_rst_stream(session, NGHTTP2_FLAG_NONE, streamId, + NGHTTP2_INTERNAL_ERROR); + } + } cn1H2ReleaseBody(s, body); } return (ssize_t)remaining; @@ -1583,7 +1796,11 @@ static long cn1H2BuildHeaders(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT status, *statusOut = NULL; *headerOut = NULL; - { + /* A NULL status builds a trailer section: the same field validation, and no + :status, which a trailer must not carry (RFC 9113 8.1). */ + if(status == JAVA_NULL) { + statusCopy = NULL; + } else { const char* tmp = stringToUTF8(threadStateData, status); if(tmp == NULL) { return -1; @@ -1626,12 +1843,14 @@ static long cn1H2BuildHeaders(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT status, *statusOut = statusCopy; *headerOut = headerCopy; - nva[count].name = (uint8_t*)":status"; - nva[count].namelen = 7; - nva[count].value = (uint8_t*)statusCopy; - nva[count].valuelen = strlen(statusCopy); - nva[count].flags = NGHTTP2_NV_FLAG_NONE; - count++; + if(statusCopy != NULL) { + nva[count].name = (uint8_t*)":status"; + nva[count].namelen = 7; + nva[count].value = (uint8_t*)statusCopy; + nva[count].valuelen = strlen(statusCopy); + nva[count].flags = NGHTTP2_NV_FLAG_NONE; + count++; + } if(headerCopy != NULL) { char* line = headerCopy; @@ -1939,6 +2158,66 @@ JAVA_INT com_codename1_backend_Http2_streamPendingImpl___long_int_R_int(CODENAME return body == NULL ? -1 : (JAVA_INT)(body->length - body->offset); } +/* + * Ends a streamed response with a trailer section. The trailer is not submitted + * here: a chunk queued by streamChunk may still be unsent, and nghttp2 requires + * the trailer to follow the last DATA frame, so it is stored on the body and + * submitted by cn1H2ReadBody when that body reaches EOF. Returns 0, or -1 when + * the stream has no open streamed response or the fields are invalid. + */ +JAVA_INT com_codename1_backend_Http2_streamEndImpl___long_int_byte_1ARRAY_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG handle, JAVA_INT streamId, JAVA_OBJECT trailers) { + CN1H2Session* s = (CN1H2Session*)(intptr_t)handle; + CN1H2Body* body = cn1H2StreamingBody(s, streamId); + nghttp2_nv nva[CN1_H2_MAX_HEADERS + 1]; + char* statusCopy = NULL; + char* block = NULL; + long count; + if(body == NULL || body->finished) { + return -1; + } + count = cn1H2BuildHeaders(threadStateData, JAVA_NULL, trailers, nva, &statusCopy, &block); + if(count < 0) { + return -1; + } + if(count > 0) { + body->trailerNva = (nghttp2_nv*)malloc((size_t)count * sizeof(nghttp2_nv)); + if(body->trailerNva == NULL) { + free(block); + return -1; + } + /* The entries point into `block`, which the body now owns with them. */ + memcpy(body->trailerNva, nva, (size_t)count * sizeof(nghttp2_nv)); + body->trailerBlock = block; + body->trailerCount = (size_t)count; + } else { + /* No fields survived (all connection-specific): end with DATA. */ + free(block); + } + body->finished = 1; + nghttp2_session_resume_data(s->session, streamId); + return 0; +} + +/* A streaming request's body bytes received since the last call, or null. */ +JAVA_OBJECT com_codename1_backend_Http2_takeDataImpl___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG handle, JAVA_INT streamId) { + CN1H2Inbound* in = cn1H2FindInbound((CN1H2Session*)(intptr_t)handle, streamId); + JAVA_OBJECT arr; + if(in == NULL || in->length == 0) { + return JAVA_NULL; + } + arr = allocArray(threadStateData, (int)in->length, &class_array1__JAVA_BYTE, sizeof(JAVA_ARRAY_BYTE), 1); + memcpy((JAVA_ARRAY_BYTE*)CN1_ARRAY_DATA(arr), in->data, in->length); + /* Back to empty rather than kept at its high-water mark: a long-lived call + that once received a large message would otherwise pin it for its life. */ + cn1H2DropInboundData(in); + return arr; +} + +JAVA_INT com_codename1_backend_Http2_remoteStateImpl___long_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG handle, JAVA_INT streamId) { + CN1H2Inbound* in = cn1H2FindInbound((CN1H2Session*)(intptr_t)handle, streamId); + return in == NULL ? -1 : (JAVA_INT)in->state; +} + JAVA_BOOLEAN com_codename1_backend_Http2_wantsMoreImpl___long_R_boolean(CODENAME_ONE_THREAD_STATE, JAVA_LONG handle) { CN1H2Session* s = (CN1H2Session*)(intptr_t)handle; if(s == NULL) { @@ -1975,5 +2254,8 @@ JAVA_VOID com_codename1_backend_Http2_destroyImpl___long(CODENAME_ONE_THREAD_STA cn1H2FreeBody(s->bodies); s->bodies = next; } + while(s->inbound != NULL) { + cn1H2FreeInbound(s, s->inbound->streamId); + } free(s); } diff --git a/vm/backend/package-docs/com/codename1/io/grpc/package-info.java b/vm/backend/package-docs/com/codename1/io/grpc/package-info.java new file mode 100644 index 00000000000..23181f73bf0 --- /dev/null +++ b/vm/backend/package-docs/com/codename1/io/grpc/package-info.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// The protobuf wire format a server shares with the client: the same +/// encoder, decoder and codec contract the application's gRPC client runs, so +/// a message encoded on a device decodes on a server byte for byte. +/// +/// - [ProtoWriter] / [ProtoReader] -- the protobuf wire format: varints, +/// zigzag integers, fixed-width numbers, length-delimited strings, bytes and +/// nested messages, and packed repeated fields. +/// - [ProtoCodec] -- encodes and decodes one message class. The build writes +/// one per `@ProtoMessage` class, `ProtoCodec`, with an `INSTANCE`. +/// - [ProtoCodecs] -- the registry of those codecs by class. +/// +/// The gRPC transport of a server is not here: calls, streaming, status codes, +/// metadata and the client channel are in `com.codename1.backend.grpc`, and a +/// service is served by a `@GrpcService` bean. +package com.codename1.io.grpc; diff --git a/vm/backend/src/com/codename1/backend/Backend.java b/vm/backend/src/com/codename1/backend/Backend.java index 2963c05d209..6fa6ea59793 100644 --- a/vm/backend/src/com/codename1/backend/Backend.java +++ b/vm/backend/src/com/codename1/backend/Backend.java @@ -962,7 +962,7 @@ public java.util.Map getHandshakeHeaders() { /// builder. private static final class Serving implements HttpServer.Handler, HttpServer.FallbackDecorator, HttpServer.UpgradeGuard, HttpServer.Forwarding, - RequestSecurity.Next { + HttpServer.GrpcHosting, RequestSecurity.Next { /// The routes the server answers on its own behalf -- MCP, the OTLP relay, /// management -- which keep their own token guards and are tried first. private final HttpServer.Handler[] own; @@ -993,6 +993,14 @@ private static final class Serving implements HttpServer.Handler, /// `cn1.server.forwardHeaders`: whose word is taken for where a request /// came from, or null for nobody's. Set once, before the server starts. ForwardedHeaders forwarded; + /// The application's gRPC server, or null. + com.codename1.backend.grpc.GrpcServer grpc; + + @Override + public com.codename1.backend.grpc.GrpcServer grpcServer() { + return grpc; + } + @Override public ForwardedHeaders forwardedHeaders() { @@ -2669,6 +2677,13 @@ public void register(HttpServer.WebSocketRegistry direct) track, active != null ? active : Tracing.NONE, inFlight, cors, Compression.fromConfig(config)); serving.forwarded = ForwardedHeaders.fromConfig(config); + // The application's gRPC services, if it has any: the HTTP/2 + // streams that carry gRPC calls are routed to them directly. + for (Object element : routers) { + if (element instanceof com.codename1.backend.grpc.GrpcServer) { + serving.grpc = (com.codename1.backend.grpc.GrpcServer) element; + } + } serving.notFound = notFoundHooks; String errorPath = config.get(Config.ERROR_PATH, "/error"); serving.errorPath = errorPath == null || errorPath.length() == 0 ? null : errorPath; diff --git a/vm/backend/src/com/codename1/backend/HttpServer.java b/vm/backend/src/com/codename1/backend/HttpServer.java index 30cfffaf955..0ca9f47ee59 100644 --- a/vm/backend/src/com/codename1/backend/HttpServer.java +++ b/vm/backend/src/com/codename1/backend/HttpServer.java @@ -7321,6 +7321,14 @@ private void serveHttp2(int fd, long session, byte[] pending, int pendingLength) requestsServed.incrementAndGet(); continue; } + if (stream.isStreaming()) { + // A gRPC call: its request messages arrive while it runs, so + // it is served here, on this connection's turn, before any of + // the body handling below, which waits for a whole body. + serveGrpc(fd, session, h2, stream, headers); + requestsServed.incrementAndGet(); + continue; + } byte[] h2RequestBody = stream.getBody(); // A body past the spool threshold arrived in a file (the native // receiver spools under the same limits as HTTP/1). Binary and @@ -7905,6 +7913,145 @@ private static boolean matchesPreface(Conn conn) { return true; } + /// Lets the handler a server is started with hand it a gRPC server, which + /// then answers every gRPC call on an HTTP/2 stream. + interface GrpcHosting { + /// The gRPC server, or null when the application has none. + com.codename1.backend.grpc.GrpcServer grpcServer(); + } + + /// Serves one gRPC call on an HTTP/2 stream. Without a gRPC server the call + /// is answered UNIMPLEMENTED, as a gRPC client expects, never a 404 page. + private void serveGrpc(int fd, long session, Http2 h2, Http2.Stream stream, Map headers) { + com.codename1.backend.grpc.GrpcServer grpc = handler instanceof GrpcHosting + ? ((GrpcHosting) handler).grpcServer() : null; + Map lines = new LinkedHashMap(); + for (Object o : headers.entrySet()) { + Map.Entry e = (Map.Entry) o; + Object k = e.getKey(); + Object v = e.getValue(); + if (k != null && v != null) { + lines.put(String.valueOf(k), String.valueOf(v)); + } + } + H2GrpcTransport transport = new H2GrpcTransport(fd, session, h2, stream.getId()); + if (grpc == null) { + grpc = new com.codename1.backend.grpc.GrpcServer(); + } + String path = stream.getPath(); + grpc.serve(transport, path == null ? "/" : path, lines); + try { + flushHttp2(fd, session, h2); + } catch (IOException gone) { + trace("fd=" + fd + " gRPC flush failed: " + gone); + } + } + + /// One gRPC call over an HTTP/2 stream. Reading waits for the peer by + /// reading the connection, which also takes in other streams' frames; they + /// are served when this call ends. + private final class H2GrpcTransport implements com.codename1.backend.grpc.GrpcServerTransport { + private final int fd; + private final long session; + private final Http2 h2; + private final int id; + private final byte[] incoming = new byte[16384]; + + H2GrpcTransport(int fd, long session, Http2 h2, int id) { + this.fd = fd; + this.session = session; + this.h2 = h2; + this.id = id; + } + + @Override + public byte[] read() throws IOException { + for (;;) { + byte[] data = h2.takeData(id); + if (data != null && data.length > 0) { + return data; + } + int state = h2.remoteState(id); + if (state > 0) { + data = h2.takeData(id); + return data != null && data.length > 0 ? data : null; + } + if (state < 0) { + throw new IOException("the gRPC stream was reset"); + } + pump(); + } + } + + private void pump() throws IOException { + flushHttp2(fd, session, h2); + int n = readFrom(fd, session, incoming, 0, incoming.length); + if (n <= 0) { + throw new IOException("HTTP/2 connection closed"); + } + h2.receive(incoming, 0, n); + } + + private void drain() throws IOException { + for (;;) { + flushHttp2(fd, session, h2); + int pending = h2.streamPending(id); + if (pending < 0) { + throw new IOException("the gRPC stream was reset"); + } + if (pending == 0) { + return; + } + int n = readFrom(fd, session, incoming, 0, incoming.length); + if (n <= 0) { + throw new IOException("HTTP/2 connection closed"); + } + h2.receive(incoming, 0, n); + } + } + + @Override + public void sendHeaders(String contentType, List lines) throws IOException { + if (!h2.respondStream(id, 200, contentType, new ArrayList(lines))) { + throw new IOException("over the response body budget"); + } + } + + @Override + public void send(byte[] data) throws IOException { + int at = 0; + while (at < data.length) { + int len = Math.min(16384, data.length - at); + byte[] chunk = new byte[len]; + System.arraycopy(data, at, chunk, 0, len); + h2.streamChunk(id, chunk, len, false); + drain(); + at += len; + } + } + + @Override + public void finish(List trailers) throws IOException { + if (trailers == null) { + h2.streamChunk(id, new byte[0], 0, true); + } else { + h2.streamEnd(id, new ArrayList(trailers)); + } + flushHttp2(fd, session, h2); + } + + @Override + public void trailersOnly(String contentType, List lines) throws IOException { + h2.respond(id, 200, contentType, new ArrayList(lines), null); + flushHttp2(fd, session, h2); + } + + @Override + public boolean isCancelled() { + return h2.remoteState(id) < 0; + } + } + private void flushHttp2(int fd, long session, Http2 h2) throws IOException { byte[] out = h2.drain(); while (out != null && out.length > 0) { diff --git a/vm/backend/src/com/codename1/backend/annotations/GrpcService.java b/vm/backend/src/com/codename1/backend/annotations/GrpcService.java new file mode 100644 index 00000000000..9562e525493 --- /dev/null +++ b/vm/backend/src/com/codename1/backend/annotations/GrpcService.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/// Makes a class a bean that serves a gRPC service. Each method carrying the +/// shared `@Rpc` annotation is one RPC of the service, and its signature decides +/// the shape: +/// +/// ```java +/// @GrpcService("shop.Inventory") +/// public class Inventory { +/// @Rpc("Get") Stock get(Item item) { ... } // unary +/// @Rpc("Watch") void watch(Item item, StreamObserver out) { ... } // server streaming +/// @Rpc("Load") Summary load(Iterator in) { ... } // client streaming +/// @Rpc("Sync") void sync(Iterator in, StreamObserver out) { ... } // bidi +/// } +/// ``` +/// +/// Request and response types are `@ProtoMessage` classes. Any shape may take a +/// `GrpcContext` as its last parameter, for metadata, the deadline and trailers. +/// A thrown `GrpcException` ends the call with its status; any other exception +/// ends it with `UNKNOWN`. The build generates the dispatch code; nothing is +/// looked up by name at run time. The service answers native gRPC on HTTP/2 and +/// gRPC-Web on HTTP/1.1, on the server's own port. +@Retention(RetentionPolicy.CLASS) +@Target(ElementType.TYPE) +public @interface GrpcService { + /// The fully qualified service name from the `.proto` file, `package.Service`. + /// + /// @return the service name + String value(); +} diff --git a/vm/backend/src/com/codename1/backend/annotations/OpenTelemetry.java b/vm/backend/src/com/codename1/backend/annotations/OpenTelemetry.java index 6c5a8c2b6d8..9f2a6303861 100644 --- a/vm/backend/src/com/codename1/backend/annotations/OpenTelemetry.java +++ b/vm/backend/src/com/codename1/backend/annotations/OpenTelemetry.java @@ -72,7 +72,8 @@ /// `OTEL_EXPORTER_OTLP_ENDPOINT` and the properties files. Empty sets nothing. String endpoint() default ""; - /// `cn1.otel.protocol`: `http/protobuf` or `http/json`. Empty sets nothing. + /// `cn1.otel.protocol`: `http/protobuf`, `http/json`, or `grpc` (the + /// collector's gRPC port, 4317 by default). Empty sets nothing. String protocol() default ""; /// `cn1.otel.sampler`, such as `traceidratio`. Empty sets nothing. diff --git a/vm/backend/src/com/codename1/backend/grpc/GrpcChannel.java b/vm/backend/src/com/codename1/backend/grpc/GrpcChannel.java new file mode 100644 index 00000000000..28aa8b61233 --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/GrpcChannel.java @@ -0,0 +1,469 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +import com.codename1.impl.backend.GrpcCallTransport; +import com.codename1.io.grpc.ProtoCodec; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +/// A gRPC client: calls the methods of a server over HTTP/2. +/// +/// ```java +/// GrpcChannel channel = GrpcChannel.forTarget("http://inventory:50051") +/// .withMetadata("authorization", "Bearer " + token) +/// .withDeadlineMillis(2000); +/// Stock stock = channel.unary("/shop.Inventory/Get", ItemCodec.INSTANCE, +/// StockCodec.INSTANCE, item); +/// ``` +/// +/// `http://` is cleartext HTTP/2 with prior knowledge, as gRPC servers listen; +/// `https://` negotiates `h2` over TLS. Every call has a connection of its own +/// and is closed when it ends, so a channel holds nothing and needs no closing. +/// +/// A non-`OK` status is thrown as a [GrpcException]; a call that never reached +/// the server is `UNAVAILABLE`. Generated `@GrpcClient` stubs call these methods. +/// +/// A [Call] is driven from one thread: a bidirectional call sends, then reads, +/// in whatever interleaving the protocol between the two programs needs. A +/// server that waits for more requests before it answers, while the client +/// waits for an answer, deadlocks the way it would with any blocking client. +public final class GrpcChannel { + private final String target; + private final List metadata; + private final long deadlineMillis; + private final int connectTimeoutMillis; + private final boolean gzip; + private final int maxMessage; + + private GrpcChannel(String target, List metadata, long deadlineMillis, + int connectTimeoutMillis, boolean gzip, int maxMessage) { + this.target = target; + this.metadata = metadata; + this.deadlineMillis = deadlineMillis; + this.connectTimeoutMillis = connectTimeoutMillis; + this.gzip = gzip; + this.maxMessage = maxMessage; + } + + /// @param target `http://host:port` or `https://host:port`, no path + /// @return a channel to it + public static GrpcChannel forTarget(String target) { + String t = target; + while (t.endsWith("/")) { + t = t.substring(0, t.length() - 1); + } + return new GrpcChannel(t, new ArrayList(), -1, 10000, false, + GrpcFrames.DEFAULT_MAX_MESSAGE); + } + + /// A channel that also sends this metadata on every call. + /// + /// @param name lower-case header name; a `-bin` name takes base64 text + /// @param value the value + /// @return the new channel + public GrpcChannel withMetadata(String name, String value) { + List m = new ArrayList(metadata); + m.add(name + ": " + value); + return new GrpcChannel(target, m, deadlineMillis, connectTimeoutMillis, gzip, maxMessage); + } + + /// A channel whose calls each have this deadline, sent as `grpc-timeout`. + /// + /// @param millis the deadline from the start of each call; negative for none + /// @return the new channel + public GrpcChannel withDeadlineMillis(long millis) { + return new GrpcChannel(target, metadata, millis, connectTimeoutMillis, gzip, maxMessage); + } + + /// @param millis the connect timeout + /// @return the new channel + public GrpcChannel withConnectTimeoutMillis(int millis) { + return new GrpcChannel(target, metadata, deadlineMillis, millis, gzip, maxMessage); + } + + /// A channel that gzips its request messages. Only for servers known to + /// accept `grpc-encoding: gzip`; responses are accepted gzipped regardless. + /// + /// @param on whether to compress + /// @return the new channel + public GrpcChannel withGzip(boolean on) { + return new GrpcChannel(target, metadata, deadlineMillis, connectTimeoutMillis, on, maxMessage); + } + + /// @param bytes the largest response message accepted + /// @return the new channel + public GrpcChannel withMaxMessageSize(int bytes) { + return new GrpcChannel(target, metadata, deadlineMillis, connectTimeoutMillis, gzip, bytes); + } + + /// @return the target + public String getTarget() { + return target; + } + + // ------------------------------------------------------------ the four shapes + + /// One request, one response. + /// + /// @param request type + /// @param response type + /// @param method `/package.Service/Method` + /// @param requestCodec the request codec + /// @param responseCodec the response codec + /// @param request the request + /// @return the response + public R unary(String method, ProtoCodec requestCodec, ProtoCodec responseCodec, + Q request) { + Call call = start(method, requestCodec, responseCodec); + try { + call.send(request); + call.complete(); + return call.single(); + } finally { + call.close(); + } + } + + /// A unary call whose messages are already encoded: the request bytes go out + /// as they are and the response comes back undecoded. For payloads built by + /// hand, such as OTLP's export requests. + /// + /// @param method `/package.Service/Method` + /// @param request the encoded request message + /// @return the encoded response message + public byte[] unary(String method, byte[] request) { + Call call = start(method, null, null); + try { + call.sendEncoded(request); + call.complete(); + if (!call.hasNext()) { + throw new GrpcException(GrpcStatus.INTERNAL, "the server sent no response message"); + } + byte[] response = call.queued.remove(0); + if (call.hasNext()) { + throw new GrpcException(GrpcStatus.INTERNAL, "the server sent more than one response"); + } + return response; + } finally { + call.close(); + } + } + + /// One request, a stream of responses, read as they arrive. The iterator + /// throws a [GrpcException] where the stream fails; read it to its end or + /// [Call#close] it. + /// + /// @param request type + /// @param response type + /// @param method `/package.Service/Method` + /// @param requestCodec the request codec + /// @param responseCodec the response codec + /// @param request the request + /// @return the responses + public Call serverStreaming(String method, ProtoCodec requestCodec, + ProtoCodec responseCodec, Q request) { + Call call = start(method, requestCodec, responseCodec); + try { + call.send(request); + call.complete(); + return call; + } catch (RuntimeException e) { + call.close(); + throw e; + } + } + + /// A stream of requests, one response. + /// + /// @param request type + /// @param response type + /// @param method `/package.Service/Method` + /// @param requestCodec the request codec + /// @param responseCodec the response codec + /// @param requests the requests, sent in order + /// @return the response + public R clientStreaming(String method, ProtoCodec requestCodec, + ProtoCodec responseCodec, Iterator requests) { + Call call = start(method, requestCodec, responseCodec); + try { + while (requests.hasNext()) { + call.send(requests.next()); + } + call.complete(); + return call.single(); + } finally { + call.close(); + } + } + + /// Streams both ways: send with [Call#send], end with [Call#complete], + /// read with the iterator, and close it in a finally. + /// + /// @param request type + /// @param response type + /// @param method `/package.Service/Method` + /// @param requestCodec the request codec + /// @param responseCodec the response codec + /// @return the call + public Call bidiStreaming(String method, ProtoCodec requestCodec, + ProtoCodec responseCodec) { + return start(method, requestCodec, responseCodec); + } + + private Call start(String method, ProtoCodec requestCodec, + ProtoCodec responseCodec) { + List headers = new ArrayList(); + headers.add("content-type: application/grpc"); + headers.add("te: trailers"); + headers.add("grpc-accept-encoding: gzip"); + if (gzip) { + headers.add("grpc-encoding: gzip"); + } + if (deadlineMillis >= 0) { + headers.add("grpc-timeout: " + GrpcMetadata.formatTimeoutMillis(deadlineMillis)); + } + headers.addAll(metadata); + boolean hasDeadline = deadlineMillis >= 0; + long now = System.nanoTime(); + long span = deadlineMillis > Long.MAX_VALUE / 1000000L ? Long.MAX_VALUE : deadlineMillis * 1000000L; + long deadline = !hasDeadline ? 0 : span > Long.MAX_VALUE - Math.max(0, now) + ? Long.MAX_VALUE : now + span; + try { + return new Call(GrpcCallTransport.open(target + method, headers, + connectTimeoutMillis, Math.min(deadlineMillis, Long.MAX_VALUE / 4000000L)), requestCodec, responseCodec, gzip, maxMessage, + hasDeadline, deadline); + } catch (IOException e) { + throw new GrpcException(GrpcStatus.UNAVAILABLE, "could not reach " + target + ": " + + e.getMessage(), e); + } + } + + /// One call in progress: send requests, end them, read responses. + /// + /// @param request type + /// @param response type + public static final class Call implements Iterator { + private final GrpcCallTransport transport; + private final ProtoCodec requestCodec; + private final ProtoCodec responseCodec; + private final boolean gzip; + private final boolean hasDeadline; + private final long deadlineNanos; + private final GrpcFrames.Decoder decoder; + final List queued = new ArrayList(); + private boolean ended; + private GrpcException endedWith; + private boolean closed; + private Map headers; + private Map trailers; + + Call(GrpcCallTransport transport, ProtoCodec requestCodec, ProtoCodec responseCodec, + boolean gzip, int maxMessage, boolean hasDeadline, long deadlineNanos) { + this.transport = transport; + this.requestCodec = requestCodec; + this.responseCodec = responseCodec; + this.gzip = gzip; + this.hasDeadline = hasDeadline; + this.deadlineNanos = deadlineNanos; + this.decoder = new GrpcFrames.Decoder(maxMessage, true); + } + + /// Sends one request message. + /// + /// @param request the message + public void send(Q request) { + byte[] frame = GrpcFrames.frame(GrpcServer.encode(requestCodec, request), gzip); + try { + transport.write(frame); + } catch (IOException e) { + throw failed(e); + } + } + + void sendEncoded(byte[] message) { + try { + transport.write(GrpcFrames.frame(message, gzip)); + } catch (IOException e) { + throw failed(e); + } + } + + /// Ends the request stream. + public void complete() { + try { + transport.endRequest(); + } catch (IOException e) { + throw failed(e); + } + } + + /// Cancels the call when it has not ended, and releases it. + public void close() { + if (!closed) { + closed = true; + transport.close(); + } + } + + /// @return the response headers, waiting for them + public Map getHeaders() { + awaitHeaders(); + return headers; + } + + /// @return the trailers, once the responses were read to their end; + /// null before + public Map getTrailers() { + return trailers; + } + + private void awaitHeaders() { + if (headers != null) { + return; + } + try { + int status = transport.status(); + headers = transport.headers(); + String grpcStatus = headers.get("grpc-status"); + if (grpcStatus == null && status != 200) { + throw new GrpcException(GrpcStatus.fromHttpStatus(status), + "HTTP status " + status); + } + String type = headers.get("content-type"); + if (grpcStatus == null && !GrpcServer.isGrpc(type)) { + throw new GrpcException(GrpcStatus.UNKNOWN, + "the response is not gRPC: content-type " + type); + } + } catch (IOException e) { + throw failed(e); + } + } + + @Override + public boolean hasNext() { + awaitHeaders(); + while (queued.isEmpty()) { + if (ended) { + if (endedWith != null) { + // A caller that caught the failure and asks again must not + // read it as a normal end of the stream. + throw endedWith; + } + return false; + } + byte[] bytes; + try { + bytes = transport.read(); + } catch (IOException e) { + throw failed(e); + } + if (bytes == null) { + finish(); + return false; + } + queued.addAll(decoder.feed(bytes, 0, bytes.length)); + } + return true; + } + + @Override + public R next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + byte[] message = queued.remove(0); + try { + return responseCodec.read(new com.codename1.io.grpc.ProtoReader(message)); + } catch (IOException e) { + throw new GrpcException(GrpcStatus.INTERNAL, "could not parse a response message", e); + } catch (RuntimeException e) { + throw new GrpcException(GrpcStatus.INTERNAL, "could not parse a response message", e); + } + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + R single() { + if (!hasNext()) { + throw new GrpcException(GrpcStatus.INTERNAL, "the server sent no response message"); + } + R r = next(); + if (hasNext()) { + throw new GrpcException(GrpcStatus.INTERNAL, "the server sent more than one response"); + } + return r; + } + + private void finish() { + ended = true; + try { + finishChecked(); + } catch (GrpcException e) { + endedWith = e; + throw e; + } + } + + private void finishChecked() { + try { + trailers = transport.trailers(); + } catch (IOException e) { + throw failed(e); + } + String s = trailers.get("grpc-status"); + if (s == null) { + s = headers.get("grpc-status"); + trailers = headers; + } + if (s == null) { + throw new GrpcException(GrpcStatus.INTERNAL, "the response carried no grpc-status"); + } + if (!decoder.isIdle()) { + throw new GrpcException(GrpcStatus.INTERNAL, "the response ended inside a message"); + } + int status = GrpcStatus.parse(s); + if (status != GrpcStatus.OK) { + String message = trailers.get("grpc-message"); + throw new GrpcException(status, message == null ? GrpcStatus.name(status) + : GrpcMetadata.decodeMessage(message)); + } + } + + private GrpcException failed(IOException e) { + close(); + if (hasDeadline && System.nanoTime() - deadlineNanos >= 0) { + return new GrpcException(GrpcStatus.DEADLINE_EXCEEDED, "deadline exceeded", e); + } + return new GrpcException(GrpcStatus.UNAVAILABLE, String.valueOf(e.getMessage()), e); + } + } +} diff --git a/vm/backend/src/com/codename1/backend/grpc/GrpcContext.java b/vm/backend/src/com/codename1/backend/grpc/GrpcContext.java new file mode 100644 index 00000000000..9aa448c0770 --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/GrpcContext.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/// What a gRPC handler can learn about its call and add to the answer: the +/// request metadata, the deadline, whether the client went away, and response +/// headers and trailers. +/// +/// Declare it as the last parameter of a `@GrpcService` method to receive it. +public final class GrpcContext { + private final String method; + private final Map metadata; + private final boolean hasDeadline; + private final long deadlineNanos; + private final GrpcServerTransport transport; + final List responseHeaders = new ArrayList(); + final List responseTrailers = new ArrayList(); + + GrpcContext(String method, Map metadata, boolean hasDeadline, long deadlineNanos, + GrpcServerTransport transport) { + this.method = method; + this.metadata = metadata; + this.hasDeadline = hasDeadline; + this.deadlineNanos = deadlineNanos; + this.transport = transport; + } + + /// @return the full method name, `/package.Service/Method` + public String getMethod() { + return method; + } + + /// A request metadata value. Names are lower case; a binary (`-bin`) + /// value is returned as the base64 text it was sent as, see [#getBinary]. + /// + /// @param name the header name + /// @return the value or null + public String get(String name) { + return metadata.get(name); + } + + /// A binary request metadata value, decoded. + /// + /// @param name a name ending in `-bin` + /// @return the bytes, or null when absent or not base64 + public byte[] getBinary(String name) { + String v = metadata.get(name); + return v == null ? null : GrpcMetadata.decodeBinary(v); + } + + /// @return every request metadata entry, read only + public Map getMetadata() { + return Collections.unmodifiableMap(metadata); + } + + /// @return milliseconds until the client's deadline, or -1 without one; + /// 0 once it has passed + public long getRemainingMillis() { + if (!hasDeadline) { + return -1; + } + long left = deadlineNanos - System.nanoTime(); + return left <= 0 ? 0 : left / 1000000L; + } + + /// @return whether the deadline has passed + public boolean isDeadlineExceeded() { + return hasDeadline && System.nanoTime() - deadlineNanos >= 0; + } + + /// @return whether the client cancelled or the stream was reset + public boolean isCancelled() { + return transport.isCancelled(); + } + + /// Adds a response header. Only effective before the first response + /// message is sent. + /// + /// @param name lower-case name + /// @param value the value + public void addHeader(String name, String value) { + responseHeaders.add(name + ": " + value); + } + + /// Adds a response trailer, sent with the status. + /// + /// @param name lower-case name, not a `grpc-` reserved one + /// @param value the value + public void addTrailer(String name, String value) { + responseTrailers.add(name + ": " + value); + } + + /// Adds a binary response trailer. + /// + /// @param name a name ending in `-bin` + /// @param value the bytes + public void addBinaryTrailer(String name, byte[] value) { + responseTrailers.add(name + ": " + GrpcMetadata.encodeBinary(value)); + } +} diff --git a/vm/backend/src/com/codename1/backend/grpc/GrpcException.java b/vm/backend/src/com/codename1/backend/grpc/GrpcException.java new file mode 100644 index 00000000000..19eff6fb051 --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/GrpcException.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +/// A failed gRPC call: a status code other than [GrpcStatus#OK] and the +/// message that goes with it. +/// +/// A server handler throws it to end a call with that status; the client throws +/// it when a call ends with one. Any other exception a handler throws is +/// reported to the caller as [GrpcStatus#UNKNOWN] with no message, so that an +/// internal error text never leaks to a peer by accident. +public class GrpcException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final int status; + + /// @param status a gRPC status code, see [GrpcStatus] + /// @param message the human-readable status message, may be null + public GrpcException(int status, String message) { + super(message); + this.status = status; + } + + /// @param status a gRPC status code, see [GrpcStatus] + /// @param message the human-readable status message, may be null + /// @param cause the underlying failure + public GrpcException(int status, String message, Throwable cause) { + super(message, cause); + this.status = status; + } + + /// @return the gRPC status code + public int getStatus() { + return status; + } + + @Override + public String toString() { + String m = getMessage(); + return "GrpcException: " + GrpcStatus.name(status) + (m == null ? "" : ": " + m); + } +} diff --git a/vm/backend/src/com/codename1/backend/grpc/GrpcFrames.java b/vm/backend/src/com/codename1/backend/grpc/GrpcFrames.java new file mode 100644 index 00000000000..e451630bc36 --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/GrpcFrames.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +/// The gRPC length-prefixed message framing: every message on a gRPC stream is +/// one byte of flags (bit 0 set when the message is compressed), a four-byte +/// big-endian length, and that many bytes of payload. +/// +/// HTTP/2 DATA frames and gRPC messages are unrelated: one DATA frame may hold +/// several messages, and one message may span many DATA frames. [Decoder] is +/// fed whatever arrived and hands back the messages that are complete, which is +/// the only correct way to read a stream. +/// +/// Rules a decoder must keep, and why: +/// +/// - The length is checked against a ceiling **before** anything is allocated. +/// Four bytes from the peer would otherwise be a 2 GB allocation on demand. +/// - A compressed flag with no negotiated encoding is a protocol error +/// (`INTERNAL`), never a guess at the codec. +/// - Any flag bit other than bit 0 is reserved; a set one is an error too. +/// - A gzip message is bounded by the same ceiling after inflation, or a small +/// message becomes a decompression bomb. +public final class GrpcFrames { + /// The prefix in front of every message. + public static final int PREFIX_LENGTH = 5; + + /// The default largest message accepted, as in grpc-java and grpc-go: 4 MB. + public static final int DEFAULT_MAX_MESSAGE = 4 * 1024 * 1024; + + private GrpcFrames() { + } + + /// Frames one message, uncompressed. + /// + /// @param message the serialized message + /// @return prefix and payload + public static byte[] frame(byte[] message) { + return frame(message, false); + } + + /// Frames one message, gzip-compressed when asked. + /// + /// @param message the serialized message + /// @param gzip whether to compress it (only when the peer accepts gzip) + /// @return prefix and payload + public static byte[] frame(byte[] message, boolean gzip) { + byte[] payload = message; + if (gzip) { + payload = gzip(message); + } + byte[] out = new byte[PREFIX_LENGTH + payload.length]; + out[0] = (byte) (gzip ? 1 : 0); + writeLength(out, 1, payload.length); + System.arraycopy(payload, 0, out, PREFIX_LENGTH, payload.length); + return out; + } + + static void writeLength(byte[] out, int offset, int length) { + out[offset] = (byte) (length >>> 24); + out[offset + 1] = (byte) (length >>> 16); + out[offset + 2] = (byte) (length >>> 8); + out[offset + 3] = (byte) length; + } + + static byte[] gzip(byte[] data) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(data.length / 2 + 32); + GZIPOutputStream out = new GZIPOutputStream(bytes); + out.write(data); + out.close(); + return bytes.toByteArray(); + } catch (IOException e) { + // Writing to memory cannot fail; this is a programming error. + throw new GrpcException(GrpcStatus.INTERNAL, "gzip failed", e); + } + } + + static byte[] gunzip(byte[] data, int max) { + try { + GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(data)); + ByteArrayOutputStream out = new ByteArrayOutputStream(Math.min(max, data.length * 4 + 64)); + byte[] buffer = new byte[8192]; + int total = 0; + int n; + while ((n = in.read(buffer, 0, buffer.length)) > 0) { + total += n; + if (total > max) { + throw new GrpcException(GrpcStatus.RESOURCE_EXHAUSTED, + "decompressed message larger than " + max + " bytes"); + } + out.write(buffer, 0, n); + } + in.close(); + return out.toByteArray(); + } catch (IOException e) { + throw new GrpcException(GrpcStatus.INTERNAL, "corrupt gzip message", e); + } + } + + /// Reassembles messages from bytes as they arrive. Not thread safe; one per + /// stream direction. + public static final class Decoder { + private final int maxMessage; + private final boolean gzipAccepted; + private final byte[] prefix = new byte[PREFIX_LENGTH]; + private int prefixFill; + private byte[] body; + private int bodyFill; + private boolean compressed; + + /// @param maxMessage the largest message accepted, compressed or not + /// @param gzipAccepted whether the peer declared `grpc-encoding: gzip` + public Decoder(int maxMessage, boolean gzipAccepted) { + this.maxMessage = maxMessage; + this.gzipAccepted = gzipAccepted; + } + + /// Feeds bytes and returns every message they completed, in order. + /// + /// @param data the bytes + /// @param offset where they start + /// @param length how many + /// @return the completed messages, possibly empty, never null + /// @throws GrpcException on a malformed or oversized message + public List feed(byte[] data, int offset, int length) { + List out = new ArrayList(); + int pos = offset; + int end = offset + length; + while (pos < end) { + if (body == null) { + int take = Math.min(PREFIX_LENGTH - prefixFill, end - pos); + System.arraycopy(data, pos, prefix, prefixFill, take); + prefixFill += take; + pos += take; + if (prefixFill < PREFIX_LENGTH) { + break; + } + startBody(); + if (body.length == 0) { + out.add(finish()); + } + continue; + } + int take = Math.min(body.length - bodyFill, end - pos); + System.arraycopy(data, pos, body, bodyFill, take); + bodyFill += take; + pos += take; + if (bodyFill == body.length) { + out.add(finish()); + } + } + return out; + } + + /// Whether the stream ended cleanly between messages. A stream that ends + /// halfway through one lost data, and the caller must say so. + /// + /// @return true when no partial message is buffered + public boolean isIdle() { + return body == null && prefixFill == 0; + } + + private void startBody() { + int flags = prefix[0] & 0xff; + if ((flags & ~1) != 0) { + throw new GrpcException(GrpcStatus.INTERNAL, "reserved message flag set: " + flags); + } + compressed = flags == 1; + if (compressed && !gzipAccepted) { + throw new GrpcException(GrpcStatus.INTERNAL, + "compressed message without a negotiated grpc-encoding"); + } + long len = ((long) (prefix[1] & 0xff) << 24) | ((prefix[2] & 0xff) << 16) + | ((prefix[3] & 0xff) << 8) | (prefix[4] & 0xff); + if (len > maxMessage) { + throw new GrpcException(GrpcStatus.RESOURCE_EXHAUSTED, + "message of " + len + " bytes exceeds the limit of " + maxMessage); + } + body = new byte[(int) len]; + bodyFill = 0; + } + + private byte[] finish() { + byte[] message = body; + body = null; + prefixFill = 0; + if (compressed) { + return gunzip(message, maxMessage); + } + return message; + } + } +} diff --git a/vm/backend/src/com/codename1/backend/grpc/GrpcMetadata.java b/vm/backend/src/com/codename1/backend/grpc/GrpcMetadata.java new file mode 100644 index 00000000000..d789d880b0a --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/GrpcMetadata.java @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +import com.codename1.backend.Base64; + +import java.io.ByteArrayOutputStream; +import java.io.UnsupportedEncodingException; + +/// The encodings gRPC layers on top of HTTP/2 headers: the `grpc-timeout` +/// deadline, the percent-encoded `grpc-message`, and binary metadata in +/// headers whose name ends in `-bin`. +/// +/// Each is small and each has been gotten wrong by somebody: a timeout whose +/// unit letter is case sensitive (`M` minutes, `m` milliseconds), a status +/// message that must survive any UTF-8 a handler puts in it, and base64 that a +/// sender may or may not pad. +public final class GrpcMetadata { + /// The suffix that marks a header as binary metadata. + public static final String BINARY_SUFFIX = "-bin"; + + private static final String HEX = "0123456789ABCDEF"; + + private GrpcMetadata() { + } + + /// Parses `grpc-timeout`: at most eight ASCII digits and a unit, one of + /// `H M S m u n`. The unit is case sensitive. + /// + /// @param value the header value, may be null + /// @return the timeout in nanoseconds, or -1 when the header is absent or + /// malformed (a malformed timeout is ignored, as grpc-java does) + public static long parseTimeoutNanos(String value) { + if (value == null || value.length() < 2 || value.length() > 9) { + return -1; + } + long n = 0; + int last = value.length() - 1; + for (int i = 0; i < last; i++) { + char c = value.charAt(i); + if (c < '0' || c > '9') { + return -1; + } + n = n * 10 + (c - '0'); + } + switch (value.charAt(last)) { + case 'H': + return saturatingMultiply(n, 3600L * 1000000000L); + case 'M': + return saturatingMultiply(n, 60L * 1000000000L); + case 'S': + return saturatingMultiply(n, 1000000000L); + case 'm': + return n * 1000000L; + case 'u': + return n * 1000L; + case 'n': + return n; + default: + return -1; + } + } + + private static long saturatingMultiply(long n, long unit) { + if (n > Long.MAX_VALUE / unit) { + return Long.MAX_VALUE; + } + return n * unit; + } + + /// Formats a timeout for `grpc-timeout`, choosing the finest unit that keeps + /// the value within eight digits. A coarser unit rounds up, so the + /// advertised deadline is never earlier than the real one. + /// + /// @param millis the remaining time in milliseconds, at least 1 + /// @return the header value + public static String formatTimeoutMillis(long millis) { + if (millis < 1) { + millis = 1; + } + if (millis < 100000000L) { + return millis + "m"; + } + long seconds = (millis + 999) / 1000; + if (seconds < 100000000L) { + return seconds + "S"; + } + long minutes = (seconds + 59) / 60; + if (minutes < 100000000L) { + return minutes + "M"; + } + long hours = (minutes + 59) / 60; + return Math.min(hours, 99999999L) + "H"; + } + + /// Percent-encodes a status message for `grpc-message`: every byte of its + /// UTF-8 form outside printable ASCII, and `%` itself, becomes `%XX`. + /// + /// @param message the message, may be null + /// @return the encoded form, empty for null + public static String encodeMessage(String message) { + if (message == null) { + return ""; + } + byte[] bytes = utf8(message); + StringBuilder out = new StringBuilder(bytes.length + 8); + for (byte raw : bytes) { + int b = raw & 0xff; + if (b < 0x20 || b > 0x7e || b == '%') { + out.append('%').append(HEX.charAt(b >> 4)).append(HEX.charAt(b & 0xf)); + } else { + out.append((char) b); + } + } + return out.toString(); + } + + /// Decodes a `grpc-message`. A malformed escape is kept as it is rather + /// than failing: the message is for people, and losing it helps nobody. + /// + /// @param value the header value, may be null + /// @return the message, or null for null + public static String decodeMessage(String value) { + if (value == null) { + return null; + } + if (value.indexOf('%') < 0) { + return value; + } + ByteArrayOutputStream out = new ByteArrayOutputStream(value.length()); + int i = 0; + while (i < value.length()) { + char c = value.charAt(i); + if (c == '%' && i + 2 < value.length()) { + int hi = hex(value.charAt(i + 1)); + int lo = hex(value.charAt(i + 2)); + if (hi >= 0 && lo >= 0) { + out.write((hi << 4) | lo); + i += 3; + continue; + } + } + out.write(c > 0xff ? '?' : c); + i++; + } + try { + return new String(out.toByteArray(), "UTF-8"); + } catch (UnsupportedEncodingException e) { + return value; + } + } + + private static int hex(char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return -1; + } + + /// Whether a header name carries binary metadata. + /// + /// @param name a header name + /// @return true for a name ending in `-bin`, compared without case + public static boolean isBinary(String name) { + int n = name.length(); + return n > BINARY_SUFFIX.length() + && name.regionMatches(true, n - BINARY_SUFFIX.length(), BINARY_SUFFIX, 0, + BINARY_SUFFIX.length()); + } + + /// Encodes binary metadata. gRPC senders omit the padding; receivers accept + /// either. + /// + /// @param value the bytes + /// @return unpadded base64 + public static String encodeBinary(byte[] value) { + String s = Base64.encode(value); + int end = s.length(); + while (end > 0 && s.charAt(end - 1) == '=') { + end--; + } + return s.substring(0, end); + } + + /// Decodes binary metadata, padded or not. + /// + /// @param value the header value + /// @return the bytes, or null when the value is not base64 + public static byte[] decodeBinary(String value) { + String s = value.trim(); + int rem = s.length() % 4; + if (rem == 1) { + return null; + } + if (rem == 2) { + s = s + "=="; + } else if (rem == 3) { + s = s + "="; + } + return Base64.decode(s); + } + + static byte[] utf8(String s) { + try { + return s.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new GrpcException(GrpcStatus.INTERNAL, "no UTF-8", e); + } + } +} diff --git a/vm/backend/src/com/codename1/backend/grpc/GrpcMethod.java b/vm/backend/src/com/codename1/backend/grpc/GrpcMethod.java new file mode 100644 index 00000000000..ea589945e02 --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/GrpcMethod.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +import com.codename1.io.grpc.ProtoCodec; + +import java.util.Iterator; + +/// One method a [GrpcServer] serves: its path, its shape, the codecs of its +/// messages and the code that runs it. +/// +/// The build generates these from `@GrpcService` beans, so nothing is looked up +/// by name at run time. They can also be built by hand with the factories. +public final class GrpcMethod { + /// One request, one response. + public static final int UNARY = 0; + /// One request, a stream of responses. + public static final int SERVER_STREAMING = 1; + /// A stream of requests, one response. + public static final int CLIENT_STREAMING = 2; + /// Streams both ways. + public static final int BIDI_STREAMING = 3; + + /// Runs a unary method. + public interface Unary { + /// @param request the request message + /// @param context the call + /// @return the response message + /// @throws Exception ends the call with a status + Object call(Object request, GrpcContext context) throws Exception; + } + + /// Runs a server streaming method. + public interface ServerStreaming { + /// @param request the request message + /// @param responses where the responses go + /// @param context the call + /// @throws Exception ends the call with a status + void call(Object request, StreamObserver responses, GrpcContext context) throws Exception; + } + + /// Runs a client streaming method. + public interface ClientStreaming { + /// @param requests the request messages, read as they arrive + /// @param context the call + /// @return the response message + /// @throws Exception ends the call with a status + Object call(Iterator requests, GrpcContext context) throws Exception; + } + + /// Runs a bidirectional streaming method. + public interface BidiStreaming { + /// @param requests the request messages, read as they arrive + /// @param responses where the responses go + /// @param context the call + /// @throws Exception ends the call with a status + void call(Iterator requests, StreamObserver responses, GrpcContext context) throws Exception; + } + + final String path; + final int kind; + final ProtoCodec requestCodec; + final ProtoCodec responseCodec; + final Object invoker; + + private GrpcMethod(String service, String method, int kind, ProtoCodec requestCodec, + ProtoCodec responseCodec, Object invoker) { + this.path = "/" + service + "/" + method; + this.kind = kind; + this.requestCodec = requestCodec; + this.responseCodec = responseCodec; + this.invoker = invoker; + } + + /// @param service the fully qualified service, `package.Service` + /// @param method the method name + /// @param req the request codec + /// @param resp the response codec + /// @param invoker the code + /// @return the method + public static GrpcMethod unary(String service, String method, ProtoCodec req, + ProtoCodec resp, Unary invoker) { + return new GrpcMethod(service, method, UNARY, req, resp, invoker); + } + + /// @param service the fully qualified service, `package.Service` + /// @param method the method name + /// @param req the request codec + /// @param resp the response codec + /// @param invoker the code + /// @return the method + public static GrpcMethod serverStreaming(String service, String method, ProtoCodec req, + ProtoCodec resp, ServerStreaming invoker) { + return new GrpcMethod(service, method, SERVER_STREAMING, req, resp, invoker); + } + + /// @param service the fully qualified service, `package.Service` + /// @param method the method name + /// @param req the request codec + /// @param resp the response codec + /// @param invoker the code + /// @return the method + public static GrpcMethod clientStreaming(String service, String method, ProtoCodec req, + ProtoCodec resp, ClientStreaming invoker) { + return new GrpcMethod(service, method, CLIENT_STREAMING, req, resp, invoker); + } + + /// @param service the fully qualified service, `package.Service` + /// @param method the method name + /// @param req the request codec + /// @param resp the response codec + /// @param invoker the code + /// @return the method + public static GrpcMethod bidiStreaming(String service, String method, ProtoCodec req, + ProtoCodec resp, BidiStreaming invoker) { + return new GrpcMethod(service, method, BIDI_STREAMING, req, resp, invoker); + } + + /// @return `/package.Service/Method` + public String getPath() { + return path; + } + + /// @return one of [#UNARY], [#SERVER_STREAMING], [#CLIENT_STREAMING], [#BIDI_STREAMING] + public int getKind() { + return kind; + } +} diff --git a/vm/backend/src/com/codename1/backend/grpc/GrpcServer.java b/vm/backend/src/com/codename1/backend/grpc/GrpcServer.java new file mode 100644 index 00000000000..fc334b9da9d --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/GrpcServer.java @@ -0,0 +1,552 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +import com.codename1.backend.HttpServer; +import com.codename1.backend.log.Logger; +import com.codename1.io.grpc.ProtoCodec; +import com.codename1.io.grpc.ProtoReader; +import com.codename1.io.grpc.ProtoWriter; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +/// Serves gRPC: native gRPC over HTTP/2, and gRPC-Web over HTTP/1.1 or HTTP/2 +/// for browsers and for the Codename One client's `GrpcWeb`. +/// +/// The build creates one from the module's `@GrpcService` beans and the HTTP +/// server routes every `application/grpc*` request on an HTTP/2 stream to it. +/// It is also an ordinary [HttpServer.Handler], which is how gRPC-Web reaches it +/// over HTTP/1.1. +/// +/// Rules it keeps, each of which a real client depends on: +/// +/// - The answer is always HTTP 200 with the outcome in `grpc-status`; a call that +/// fails before its first message is a "trailers-only" response. +/// - An unknown method is `UNIMPLEMENTED`, a `grpc-encoding` other than +/// `identity` or `gzip` is `UNIMPLEMENTED` with the accepted encodings named. +/// - A unary or server streaming call that sends no request, or more than one, +/// is `INTERNAL`, as in grpc-java. +/// - The `grpc-timeout` deadline is checked before the handler runs, before each +/// response message and after the handler returns. A handler blocked in its +/// own code is not interrupted; [GrpcContext#isDeadlineExceeded] lets it stop. +/// - An exception that is not a [GrpcException] is logged here and reported as +/// `UNKNOWN` with no message, so an internal error text never reaches a peer. +/// +/// Not supported: `application/grpc-web-text` (base64 framing), and server +/// reflection. Calls on one HTTP/2 connection are served one at a time, in the +/// connection's turn, as the server serves every HTTP/2 request; a client that +/// wants concurrent streaming calls opens more connections. +public final class GrpcServer implements HttpServer.Handler { + private static final Logger LOG = Logger.getLogger(GrpcServer.class); + private static final String GRPC = "application/grpc"; + private static final String GRPC_WEB = "application/grpc-web"; + private static final String GRPC_WEB_PROTO = "application/grpc-web+proto"; + private static final Object END = new Object(); + + private final Map methods = new HashMap(); + private int maxMessage = GrpcFrames.DEFAULT_MAX_MESSAGE; + + /// Adds a method. A second method on the same path replaces the first. + /// + /// @param method the method + /// @return this + public GrpcServer add(GrpcMethod method) { + methods.put(method.getPath(), method); + return this; + } + + /// The largest request message accepted, compressed or not. + /// + /// @param bytes the limit; 4 MB by default + /// @return this + public GrpcServer setMaxMessageSize(int bytes) { + this.maxMessage = bytes; + return this; + } + + /// @param path `/package.Service/Method` + /// @return whether this server has the method + public boolean has(String path) { + return methods.containsKey(path); + } + + /// Whether a content type is one this server answers. + /// + /// @param contentType the request's content type, may be null + /// @return true for `application/grpc` and its variants + public static boolean isGrpc(String contentType) { + if (contentType == null || !contentType.regionMatches(true, 0, GRPC, 0, GRPC.length())) { + return false; + } + // application/grpc, application/grpc+proto or application/grpc;params; not + // application/grpc-web, which is a different framing. + if (contentType.length() == GRPC.length()) { + return true; + } + char next = contentType.charAt(GRPC.length()); + return next == '+' || next == ';'; + } + + private static boolean isWeb(String contentType) { + return contentType != null + && contentType.regionMatches(true, 0, GRPC_WEB, 0, GRPC_WEB.length()); + } + + // ------------------------------------------------------------ gRPC-Web, HTTP/1.1 + + /// Answers gRPC-Web requests arriving as ordinary HTTP requests; anything + /// else is left to the next handler. + @Override + public HttpServer.Response handle(final HttpServer.Request request) throws Exception { + final String type = request.getHeader("content-type"); + if (!isWeb(type)) { + return null; + } + if (!"POST".equals(request.getMethod())) { + return HttpServer.Response.text(405, "gRPC-Web requires POST"); + } + final Map headers = headerMap(request.getHeaders()); + final byte[] body = request.getBodyBytes(); + final String target = request.getTarget(); + return HttpServer.Response.stream(200, GRPC_WEB_PROTO, new HttpServer.BodyWriter() { + @Override + public void writeTo(OutputStream output) throws IOException { + serve(new BufferedWebTransport(body, output), target, headers); + } + }); + } + + private static Map headerMap(Map raw) { + Map out = new LinkedHashMap(); + if (raw != null) { + for (Object o : raw.entrySet()) { + Map.Entry e = (Map.Entry) o; + Object k = e.getKey(); + Object v = e.getValue(); + if (k != null && v != null) { + out.put(String.valueOf(k), v instanceof List + ? join((List) v) : String.valueOf(v)); + } + } + } + return out; + } + + private static String join(List values) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < values.size(); i++) { + if (i > 0) { + b.append(','); + } + b.append(values.get(i)); + } + return b.toString(); + } + + /// gRPC-Web over a buffered HTTP/1.1 request: the whole request body is + /// known up front, and the response status and type are already decided by + /// the time the body is written, so headers travel in the trailer frame. + private static final class BufferedWebTransport implements GrpcServerTransport { + private byte[] body; + private final OutputStream out; + + BufferedWebTransport(byte[] body, OutputStream out) { + this.body = body == null ? new byte[0] : body; + this.out = out; + } + + @Override + public byte[] read() { + byte[] b = body; + body = null; + return b; + } + + @Override + public void sendHeaders(String contentType, List lines) { + // Already sent by the HTTP layer as 200 with the gRPC-Web type. + } + + @Override + public void send(byte[] data) throws IOException { + out.write(data); + out.flush(); + } + + @Override + public void finish(List trailers) throws IOException { + out.flush(); + } + + @Override + public void trailersOnly(String contentType, List lines) throws IOException { + out.write(webTrailerFrame(lines)); + out.flush(); + } + + @Override + public boolean isCancelled() { + return false; + } + } + + static byte[] webTrailerFrame(List lines) { + StringBuilder b = new StringBuilder(); + for (String line : lines) { + int colon = line.indexOf(':'); + b.append(line, 0, colon).append(':').append(line.substring(colon + 1).trim()).append("\r\n"); + } + byte[] text = GrpcMetadata.utf8(b.toString()); + byte[] frame = new byte[GrpcFrames.PREFIX_LENGTH + text.length]; + frame[0] = (byte) 0x80; + GrpcFrames.writeLength(frame, 1, text.length); + System.arraycopy(text, 0, frame, GrpcFrames.PREFIX_LENGTH, text.length); + return frame; + } + + // ------------------------------------------------------------ one call + + /// Serves one call over a transport. Never throws: every outcome becomes a + /// gRPC status, and a transport that fails ends the call silently. + /// + /// @param transport the HTTP side + /// @param target the request target, `/package.Service/Method` + /// @param headers the request headers, lower-case names + public void serve(GrpcServerTransport transport, String target, Map headers) { + String type = headers.get("content-type"); + boolean web = isWeb(type); + String responseType = web ? GRPC_WEB_PROTO : GRPC; + String path = target; + int q = path.indexOf('?'); + if (q >= 0) { + path = path.substring(0, q); + } + try { + if (web && type.regionMatches(true, 0, "application/grpc-web-text", 0, 25)) { + refuse(transport, responseType, GrpcStatus.UNIMPLEMENTED, + "application/grpc-web-text is not supported", null); + return; + } + GrpcMethod method = methods.get(path); + if (method == null) { + refuse(transport, responseType, GrpcStatus.UNIMPLEMENTED, + "unknown method " + path, null); + return; + } + String encoding = headers.get("grpc-encoding"); + boolean gzip = false; + if (encoding != null && !"identity".equalsIgnoreCase(encoding)) { + if (!"gzip".equalsIgnoreCase(encoding)) { + refuse(transport, responseType, GrpcStatus.UNIMPLEMENTED, + "unsupported grpc-encoding " + encoding, "grpc-accept-encoding: gzip"); + return; + } + gzip = true; + } + long timeout = GrpcMetadata.parseTimeoutNanos(headers.get("grpc-timeout")); + // nanoTime has an arbitrary origin, so "no deadline" is its own flag, and a + // saturated timeout must not wrap the sum into the past. + boolean hasDeadline = timeout >= 0; + long now = System.nanoTime(); + long deadline = !hasDeadline ? 0 : timeout > Long.MAX_VALUE - Math.max(0, now) + ? Long.MAX_VALUE : now + timeout; + Map metadata = new LinkedHashMap(); + for (Map.Entry e : headers.entrySet()) { + String name = e.getKey(); + if (!name.startsWith(":") && !name.startsWith("grpc-") && !"te".equals(name) + && !"content-type".equals(name) && !"content-length".equals(name)) { + metadata.put(name, e.getValue()); + } + } + GrpcContext context = new GrpcContext(path, metadata, hasDeadline, deadline, transport); + new Call(this, method, transport, context, responseType, web, gzip).run(); + } catch (IOException gone) { + // The client went away; there is nobody to tell. + } + } + + private static void refuse(GrpcServerTransport t, String type, int status, String message, + String extra) throws IOException { + List lines = new ArrayList(); + lines.add("grpc-status: " + status); + lines.add("grpc-message: " + GrpcMetadata.encodeMessage(message)); + if (extra != null) { + lines.add(extra); + } + t.trailersOnly(type, lines); + } + + static byte[] encode(ProtoCodec codec, Object value) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + codec.write(new ProtoWriter(bytes), value); + return bytes.toByteArray(); + } catch (IOException e) { + throw new GrpcException(GrpcStatus.INTERNAL, "could not encode a message", e); + } + } + + static Object decode(ProtoCodec codec, byte[] message) { + try { + return codec.read(new ProtoReader(message)); + } catch (IOException e) { + throw new GrpcException(GrpcStatus.INTERNAL, "could not parse a request message", e); + } catch (RuntimeException e) { + throw new GrpcException(GrpcStatus.INTERNAL, "could not parse a request message", e); + } + } + + /// The state of one call: reading requests, sending responses, ending once. + private static final class Call implements Iterator, StreamObserver { + private final GrpcMethod method; + private final GrpcServerTransport transport; + private final GrpcContext context; + private final String responseType; + private final boolean web; + private final GrpcFrames.Decoder decoder; + private final List queued = new ArrayList(); + private boolean inputEnded; + private Object peeked; + private boolean headersSent; + private boolean finished; + + Call(GrpcServer server, GrpcMethod method, GrpcServerTransport transport, + GrpcContext context, String responseType, boolean web, boolean gzip) { + this.method = method; + this.transport = transport; + this.context = context; + this.responseType = responseType; + this.web = web; + this.decoder = new GrpcFrames.Decoder(server.maxMessage, gzip); + } + + void run() throws IOException { + try { + checkDeadline(); + switch (method.kind) { + case GrpcMethod.UNARY: { + Object request = single(); + Object response = ((GrpcMethod.Unary) method.invoker).call(request, context); + checkDeadline(); + if (response == null) { + throw new GrpcException(GrpcStatus.INTERNAL, "the handler returned null"); + } + onNext(response); + break; + } + case GrpcMethod.SERVER_STREAMING: + ((GrpcMethod.ServerStreaming) method.invoker).call(single(), this, context); + break; + case GrpcMethod.CLIENT_STREAMING: { + Object response = ((GrpcMethod.ClientStreaming) method.invoker).call(this, context); + checkDeadline(); + if (response == null) { + throw new GrpcException(GrpcStatus.INTERNAL, "the handler returned null"); + } + onNext(response); + break; + } + default: + ((GrpcMethod.BidiStreaming) method.invoker).call(this, this, context); + break; + } + if (!finished) { + checkDeadline(); + end(GrpcStatus.OK, null); + } + } catch (GrpcException e) { + end(e.getStatus(), e.getMessage()); + } catch (TransportFailed e) { + throw e.cause; + } catch (StackOverflowError e) { + // A runaway handler, not a broken VM: the call fails, the server goes on. + LOG.error("gRPC method {} failed", method.path, e); + end(GrpcStatus.UNKNOWN, null); + } catch (VirtualMachineError e) { + throw e; + } catch (Throwable e) { //NOPMD AvoidCatchingThrowable - every handler failure must become a status + LOG.error("gRPC method {} failed", method.path, e); + end(GrpcStatus.UNKNOWN, null); + } + } + + private void checkDeadline() { + if (context.isDeadlineExceeded()) { + throw new GrpcException(GrpcStatus.DEADLINE_EXCEEDED, "deadline exceeded"); + } + } + + private Object single() { + if (!hasNext()) { + throw new GrpcException(GrpcStatus.INTERNAL, "the call carried no request message"); + } + Object request = next(); + if (hasNext()) { + throw new GrpcException(GrpcStatus.INTERNAL, + "a unary call carried more than one request message"); + } + return request; + } + + // ---- Iterator over request messages + + @Override + public boolean hasNext() { + if (peeked == null) { + peeked = fetch(); + } + return peeked != END; + } + + @Override + public Object next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + Object m = peeked; + peeked = null; + return m; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + private Object fetch() { + while (queued.isEmpty()) { + if (inputEnded) { + return END; + } + byte[] bytes; + try { + bytes = transport.read(); + } catch (IOException e) { + throw new TransportFailed(e); + } + if (bytes == null) { + inputEnded = true; + if (!decoder.isIdle()) { + throw new GrpcException(GrpcStatus.INTERNAL, "the request ended inside a message"); + } + } else { + queued.addAll(decoder.feed(bytes, 0, bytes.length)); + } + } + return decode(method.requestCodec, queued.remove(0)); + } + + // ---- StreamObserver over responses + + @Override + public void onNext(Object value) { + if (finished) { + throw new IllegalStateException("the call already ended"); + } + if (transport.isCancelled()) { + throw new GrpcException(GrpcStatus.CANCELLED, "the client cancelled the call"); + } + checkDeadline(); + byte[] frame = GrpcFrames.frame(encode(method.responseCodec, value)); + try { + if (!headersSent) { + headersSent = true; + List lines = new ArrayList(context.responseHeaders); + lines.add("grpc-accept-encoding: gzip"); + transport.sendHeaders(responseType, lines); + } + transport.send(frame); + } catch (IOException e) { + throw new TransportFailed(e); + } + } + + @Override + public void onError(Throwable error) { + if (error instanceof GrpcException) { + GrpcException g = (GrpcException) error; + endQuietly(g.getStatus(), g.getMessage()); + } else { + LOG.error("gRPC method {} failed", method.path, error); + endQuietly(GrpcStatus.UNKNOWN, null); + } + } + + @Override + public void onCompleted() { + endQuietly(GrpcStatus.OK, null); + } + + private void endQuietly(int status, String message) { + try { + end(status, message); + } catch (IOException e) { + throw new TransportFailed(e); + } + } + + private void end(int status, String message) throws IOException { + if (finished) { + return; + } + finished = true; + List trailers = new ArrayList(); + trailers.add("grpc-status: " + status); + if (message != null && message.length() > 0) { + trailers.add("grpc-message: " + GrpcMetadata.encodeMessage(message)); + } + trailers.addAll(context.responseTrailers); + if (!headersSent) { + List lines = new ArrayList(context.responseHeaders); + lines.addAll(trailers); + transport.trailersOnly(responseType, lines); + } else if (web) { + transport.send(webTrailerFrame(trailers)); + transport.finish(null); + } else { + transport.finish(trailers); + } + } + } + + /// A transport failure carried out of the iterator and the observer, whose + /// signatures cannot throw IOException; unwrapped in [Call#run]. + private static final class TransportFailed extends RuntimeException { + private static final long serialVersionUID = 1L; + final IOException cause; + + TransportFailed(IOException cause) { + super(cause); + this.cause = cause; + } + } +} diff --git a/vm/backend/src/com/codename1/backend/grpc/GrpcServerTransport.java b/vm/backend/src/com/codename1/backend/grpc/GrpcServerTransport.java new file mode 100644 index 00000000000..a3854557437 --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/GrpcServerTransport.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +import java.io.IOException; +import java.util.List; + +/// The HTTP side of one gRPC call on the server, implemented by the HTTP +/// server for an HTTP/2 stream and by [GrpcServer] for gRPC-Web over HTTP/1.1. +/// +/// Header lines are `name: value` strings. +public interface GrpcServerTransport { + /// The next request bytes, blocking until some arrive. + /// + /// @return the bytes, or null once the client ended its side + /// @throws IOException when the stream was reset or the connection failed + byte[] read() throws IOException; + + /// Sends the response headers: status 200 and this content type. + /// + /// @param contentType the response content type + /// @param lines further headers + /// @throws IOException when the stream is gone + void sendHeaders(String contentType, List lines) throws IOException; + + /// Sends response bytes, after [#sendHeaders]. + /// + /// @param data the bytes + /// @throws IOException when the stream is gone + void send(byte[] data) throws IOException; + + /// Ends the response with these trailers, after [#sendHeaders]; null ends + /// it with no trailers. + /// + /// @param trailers the trailer lines, or null + /// @throws IOException when the stream is gone + void finish(List trailers) throws IOException; + + /// Answers with headers only, ending the stream: a gRPC "trailers-only" + /// response, used when the call fails before any message was sent. + /// + /// @param contentType the response content type + /// @param lines the headers, the status among them + /// @throws IOException when the stream is gone + void trailersOnly(String contentType, List lines) throws IOException; + + /// @return whether the client cancelled or the stream was reset + boolean isCancelled(); +} diff --git a/vm/backend/src/com/codename1/backend/grpc/GrpcStatus.java b/vm/backend/src/com/codename1/backend/grpc/GrpcStatus.java new file mode 100644 index 00000000000..50514d327cb --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/GrpcStatus.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +/// The gRPC status codes, as they travel in the `grpc-status` trailer. +/// +/// The numbers are the wire values from the gRPC specification and never change; +/// the names are the ones every gRPC implementation prints, so a log line here +/// reads the same as one from the peer. +public final class GrpcStatus { + /// Not an error: the call completed. + public static final int OK = 0; + /// The call was cancelled, usually by the caller. + public static final int CANCELLED = 1; + /// An error that fits no other code. + public static final int UNKNOWN = 2; + /// The caller sent an argument that is invalid whatever the server's state. + public static final int INVALID_ARGUMENT = 3; + /// The deadline passed before the call completed. + public static final int DEADLINE_EXCEEDED = 4; + /// The requested entity does not exist. + public static final int NOT_FOUND = 5; + /// The entity the caller tried to create already exists. + public static final int ALREADY_EXISTS = 6; + /// The caller is not allowed to do this. + public static final int PERMISSION_DENIED = 7; + /// A resource, such as a quota or a message size limit, ran out. + public static final int RESOURCE_EXHAUSTED = 8; + /// The system is not in the state the call requires. + public static final int FAILED_PRECONDITION = 9; + /// The call was aborted, typically by a concurrency conflict. + public static final int ABORTED = 10; + /// A value was outside the valid range. + public static final int OUT_OF_RANGE = 11; + /// The method is not implemented by this server. + public static final int UNIMPLEMENTED = 12; + /// An invariant the server relies on was broken. + public static final int INTERNAL = 13; + /// The service is currently unavailable; a retry may succeed. + public static final int UNAVAILABLE = 14; + /// Data was lost or corrupted. + public static final int DATA_LOSS = 15; + /// The caller has no valid credentials. + public static final int UNAUTHENTICATED = 16; + + private static final String[] NAMES = { + "OK", "CANCELLED", "UNKNOWN", "INVALID_ARGUMENT", "DEADLINE_EXCEEDED", + "NOT_FOUND", "ALREADY_EXISTS", "PERMISSION_DENIED", "RESOURCE_EXHAUSTED", + "FAILED_PRECONDITION", "ABORTED", "OUT_OF_RANGE", "UNIMPLEMENTED", + "INTERNAL", "UNAVAILABLE", "DATA_LOSS", "UNAUTHENTICATED" + }; + + private GrpcStatus() { + } + + /// The conventional name of a code, or `CODE_` for one outside the table. + /// + /// @param code a gRPC status code + /// @return its name + public static String name(int code) { + if (code >= 0 && code < NAMES.length) { + return NAMES[code]; + } + return "CODE_" + code; + } + + /// The status a gRPC client must report for an HTTP response that carried no + /// `grpc-status` at all, per the gRPC "HTTP to gRPC status code mapping". + /// + /// @param httpStatus the HTTP status of the response + /// @return the gRPC code to report + public static int fromHttpStatus(int httpStatus) { + switch (httpStatus) { + case 400: + return INTERNAL; + case 401: + return UNAUTHENTICATED; + case 403: + return PERMISSION_DENIED; + case 404: + return UNIMPLEMENTED; + case 429: + case 502: + case 503: + case 504: + return UNAVAILABLE; + default: + return UNKNOWN; + } + } + + /// Parses a `grpc-status` value. Anything that is not a plain decimal number + /// is a peer speaking something other than gRPC, reported as `UNKNOWN`. + /// + /// @param value the trailer value, possibly null + /// @return the code, or `UNKNOWN` when the value is missing or malformed + public static int parse(String value) { + if (value == null || value.length() == 0 || value.length() > 9) { + return UNKNOWN; + } + int n = 0; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c < '0' || c > '9') { + return UNKNOWN; + } + n = n * 10 + (c - '0'); + } + return n; + } +} diff --git a/vm/backend/src/com/codename1/backend/grpc/StreamObserver.java b/vm/backend/src/com/codename1/backend/grpc/StreamObserver.java new file mode 100644 index 00000000000..c2ff61249bf --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/StreamObserver.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.grpc; + +/// Receives the messages of a stream: the responses a streaming handler sends, +/// or the responses a client reads from a streaming call. +/// +/// A handler calls [#onNext] once per message and ends the call with exactly one +/// of [#onCompleted] or [#onError]. Returning from a server streaming handler +/// without either completes the call with `OK`. +/// +/// @param the message type +public interface StreamObserver { + /// Sends (or receives) one message. + /// + /// @param value the message + void onNext(T value); + + /// Ends the stream with an error. A [GrpcException] carries its status; + /// anything else ends the call with `UNKNOWN`. + /// + /// @param error the failure + void onError(Throwable error); + + /// Ends the stream with `OK`. + void onCompleted(); +} diff --git a/vm/backend/src/com/codename1/backend/grpc/package-info.java b/vm/backend/src/com/codename1/backend/grpc/package-info.java new file mode 100644 index 00000000000..684876d79d3 --- /dev/null +++ b/vm/backend/src/com/codename1/backend/grpc/package-info.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// gRPC for the backend: the length-prefixed message framing, the status codes +/// and the header encodings gRPC adds on top of HTTP/2. +/// +/// [com.codename1.backend.grpc.GrpcFrames] reassembles messages from the bytes of +/// a stream, [com.codename1.backend.grpc.GrpcStatus] names the codes a call ends +/// with, and [com.codename1.backend.grpc.GrpcMetadata] handles `grpc-timeout`, +/// `grpc-message` and binary `-bin` metadata. +package com.codename1.backend.grpc; diff --git a/vm/backend/src/com/codename1/backend/otel/BatchExporter.java b/vm/backend/src/com/codename1/backend/otel/BatchExporter.java index 0f3e0035114..efd25d6d409 100644 --- a/vm/backend/src/com/codename1/backend/otel/BatchExporter.java +++ b/vm/backend/src/com/codename1/backend/otel/BatchExporter.java @@ -107,6 +107,13 @@ final class BatchExporter implements Runnable { this.maxRelayBytes = maxRelayBytes; } + /// Set when the protocol is gRPC: the gRPC target exports go to. + private String grpcTarget; + + void useGrpc(String target) { + grpcTarget = target; + } + boolean isProtobuf() { return protobuf; } @@ -466,6 +473,19 @@ private int post(byte[] body, String contentType) { lines.add("Content-Type: " + contentType); lines.addAll(headers); int status; + if (grpcTarget != null) { + Object[] r = OtlpGrpc.export(grpcTarget, OtlpGrpc.TRACES, headers, body); + status = ((Integer) r[0]).intValue(); + if (status == 200) { + byte[] response = (byte[]) r[1]; + if (response != null && response.length > 0) { + lastRejected = grpcPartialSuccess(response); + } + return SENT; + } + recordFailure((String) r[2]); + return status == 503 || status == 429 || status == 504 ? RETRY : FAILED; + } try { Web.Result result = Web.request("POST", endpoint, lines, body); status = result.getStatus(); @@ -495,6 +515,21 @@ private int post(byte[] body, String contentType) { /// what a 200 without the field means. /// /// @return the number of spans rejected, 0 for none + private long grpcPartialSuccess(byte[] response) { + long[] rejected = new long[1]; + String[] message = new String[1]; + try { + OtlpSchema.protobufPartialSuccess(response, rejected, message); + } catch (Exception err) { + return 0; + } + if (rejected[0] > 0) { + recordFailure("the collector rejected " + rejected[0] + " span(s)" + + (message[0] == null || message[0].length() == 0 ? "" : ": " + message[0])); + } + return rejected[0] < 0 ? 0 : rejected[0]; + } + private long partialSuccess(Web.Result result, String requestType) { byte[] body = result.getBody(); if (body == null || body.length == 0) { diff --git a/vm/backend/src/com/codename1/backend/otel/OtlpGrpc.java b/vm/backend/src/com/codename1/backend/otel/OtlpGrpc.java new file mode 100644 index 00000000000..7d30f105258 --- /dev/null +++ b/vm/backend/src/com/codename1/backend/otel/OtlpGrpc.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.backend.otel; + +import com.codename1.backend.grpc.GrpcChannel; +import com.codename1.backend.grpc.GrpcException; +import com.codename1.backend.grpc.GrpcStatus; + +import java.util.List; + +/// OTLP over gRPC (`cn1.otel.protocol=grpc`): the same protobuf export +/// requests the HTTP exporters build, sent as unary calls to the collector's +/// `TraceService/Export` and `MetricsService/Export`, by default on port 4317. +/// +/// The outcome is reported as the HTTP status the exporters already act on, +/// so retries follow one rule: `UNAVAILABLE`, `RESOURCE_EXHAUSTED` and +/// `DEADLINE_EXCEEDED` are retried, as the OTLP specification lists them; +/// anything else drops the batch. +final class OtlpGrpc { + static final String TRACES = "/opentelemetry.proto.collector.trace.v1.TraceService/Export"; + static final String METRICS = "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export"; + private static final long DEADLINE_MILLIS = 10000; + + private OtlpGrpc() { + } + + /// The gRPC target of an endpoint setting: scheme, host and port, with any + /// path dropped, since a gRPC method names its own. + static String target(String endpoint) { + String e = endpoint.trim(); + int scheme = e.indexOf("://"); + int slash = scheme < 0 ? -1 : e.indexOf('/', scheme + 3); + return slash < 0 ? e : e.substring(0, slash); + } + + /// Sends one export request. + /// + /// @param target `http://host:port` or `https://host:port` + /// @param method [#TRACES] or [#METRICS] + /// @param headers "Name: value" lines from the headers setting + /// @param body the protobuf export request + /// @return {Integer status, byte[] response or null, String error or null} + static Object[] export(String target, String method, List headers, byte[] body) { + GrpcChannel channel = GrpcChannel.forTarget(target).withDeadlineMillis(DEADLINE_MILLIS); + for (Object o : headers) { + String line = String.valueOf(o); + int colon = line.indexOf(':'); + if (colon > 0) { + channel = channel.withMetadata(asciiLower(line.substring(0, colon).trim()), + line.substring(colon + 1).trim()); + } + } + try { + byte[] response = channel.unary(method, body); + return new Object[] {Integer.valueOf(200), response, null}; + } catch (GrpcException e) { + int status; + switch (e.getStatus()) { + // The statuses the OTLP/gRPC specification calls retryable. + case GrpcStatus.UNAVAILABLE: + case GrpcStatus.CANCELLED: + case GrpcStatus.ABORTED: + case GrpcStatus.OUT_OF_RANGE: + case GrpcStatus.DATA_LOSS: + status = 503; + break; + case GrpcStatus.RESOURCE_EXHAUSTED: + status = 429; + break; + case GrpcStatus.DEADLINE_EXCEEDED: + status = 504; + break; + default: + status = 400; + break; + } + return new Object[] {Integer.valueOf(status), null, + "gRPC " + GrpcStatus.name(e.getStatus()) + ": " + e.getMessage()}; + } catch (RuntimeException e) { + // A bad target or a malformed reply must not unwind the exporter thread; + // report it as a failed attempt like any unreachable collector. + return new Object[] {Integer.valueOf(-1), null, "gRPC export failed: " + e}; + } + } + + private static String asciiLower(String s) { + StringBuilder b = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + b.append(c >= 'A' && c <= 'Z' ? (char) (c + 32) : c); + } + return b.toString(); + } +} diff --git a/vm/backend/src/com/codename1/backend/otel/OtlpMetricExporter.java b/vm/backend/src/com/codename1/backend/otel/OtlpMetricExporter.java index a84177df742..0ae071aad67 100644 --- a/vm/backend/src/com/codename1/backend/otel/OtlpMetricExporter.java +++ b/vm/backend/src/com/codename1/backend/otel/OtlpMetricExporter.java @@ -58,6 +58,8 @@ public final class OtlpMetricExporter implements MetricReader { private final String defaultServiceName; private String endpoint; + /// The gRPC target when the protocol is grpc, else null. + private String grpcTarget; private List headers = new ArrayList(); private boolean protobuf; private int intervalMillis; @@ -98,19 +100,20 @@ public boolean open(Config config) throws IOException { String protocol = config.get(PROTOCOL, config.get(OtlpTracer.PROTOCOL, "http/protobuf")).trim(); boolean asProtobuf; - if ("http/protobuf".equals(protocol)) { + boolean grpc = "grpc".equals(protocol); + if ("http/protobuf".equals(protocol) || grpc) { asProtobuf = true; } else if ("http/json".equals(protocol)) { asProtobuf = false; } else { - throw new IOException(PROTOCOL + " is '" + protocol + "'; this server exports " - + "OTLP over HTTP, so use http/protobuf or http/json"); + throw new IOException(PROTOCOL + " is '" + protocol + "'; use grpc, " + + "http/protobuf or http/json"); } String target = config.get(ENDPOINT); if (target == null || target.trim().length() == 0) { - target = OtlpTracer.appendSignalPath( - config.get(OtlpTracer.ENDPOINT, "http://localhost:4318").trim(), - "/v1/metrics"); + String base = config.get(OtlpTracer.ENDPOINT, grpc ? "http://localhost:4317" + : "http://localhost:4318").trim(); + target = grpc ? base : OtlpTracer.appendSignalPath(base, "/v1/metrics"); } String url = target.trim(); if (!OtlpTracer.hasHttpAuthority(url)) { @@ -162,6 +165,7 @@ public boolean open(Config config) throws IOException { } protobuf = asProtobuf; endpoint = url; + grpcTarget = grpc ? OtlpGrpc.target(url) : null; headers = sent; intervalMillis = interval; resource = describedAs; @@ -325,6 +329,41 @@ private void loop(Run mine) { export(); } + private boolean exportGrpc(byte[] body) { + Object[] r = OtlpGrpc.export(grpcTarget, OtlpGrpc.METRICS, headers, body); + long[] rejected = new long[1]; + String[] message = new String[1]; + boolean partial = false; + if (r[1] != null && ((byte[]) r[1]).length > 0) { + try { + OtlpSchema.protobufPartialSuccess((byte[]) r[1], rejected, message); + partial = rejected[0] > 0; + } catch (IOException err) { + // A malformed partial-success body: the export itself was accepted. + partial = false; + } catch (RuntimeException err) { + partial = false; + } + } + synchronized (lock) { + exports++; + if (r[2] != null) { + failures++; + lastError = BatchExporter.bounded((String) r[2]); + return false; + } + if (partial) { + failures++; + rejectedDataPoints += rejected[0]; + lastError = BatchExporter.bounded("the collector rejected " + rejected[0] + + " data point(s)" + (message[0] == null || message[0].length() == 0 + ? "" : ": " + message[0])); + return false; + } + } + return true; + } + /// Sends one export now. Answers whether the collector accepted it. public boolean export() { try { @@ -335,6 +374,9 @@ public boolean export() { lines.add("Content-Type: " + (protobuf ? "application/x-protobuf" : "application/json")); lines.addAll(headers); + if (grpcTarget != null) { + return exportGrpc(body); + } Web.Result result = Web.request("POST", endpoint, lines, body); int status = result.getStatus(); synchronized (lock) { diff --git a/vm/backend/src/com/codename1/backend/otel/OtlpTracer.java b/vm/backend/src/com/codename1/backend/otel/OtlpTracer.java index a6e8f8017bc..ca3cb3c426f 100644 --- a/vm/backend/src/com/codename1/backend/otel/OtlpTracer.java +++ b/vm/backend/src/com/codename1/backend/otel/OtlpTracer.java @@ -57,7 +57,7 @@ /// | cn1.otel.endpoint | OTEL_EXPORTER_OTLP_ENDPOINT | http://localhost:4318; /v1/traces is appended | /// | cn1.otel.traces.endpoint | OTEL_EXPORTER_OTLP_TRACES_ENDPOINT | used as it is, and wins over the one above | /// | cn1.otel.headers | OTEL_EXPORTER_OTLP_HEADERS | none; `name=value,name=value` | -/// | cn1.otel.protocol | OTEL_EXPORTER_OTLP_PROTOCOL | http/protobuf, or http/json | +/// | cn1.otel.protocol | OTEL_EXPORTER_OTLP_PROTOCOL | http/protobuf, http/json, or grpc (port 4317) | /// | cn1.otel.service.name | OTEL_SERVICE_NAME | what the build named it, else unknown_service | /// | cn1.otel.resource.attributes | OTEL_RESOURCE_ATTRIBUTES | none | /// | cn1.otel.sampler | OTEL_TRACES_SAMPLER | parentbased_always_on | @@ -165,7 +165,8 @@ public boolean open(Config config) throws IOException { String protocol = config.get(TRACES_PROTOCOL, config.get(PROTOCOL, "http/protobuf")).trim(); boolean protobuf; - if ("http/protobuf".equals(protocol)) { + boolean grpc = "grpc".equals(protocol); + if ("http/protobuf".equals(protocol) || grpc) { protobuf = true; } else if ("http/json".equals(protocol)) { protobuf = false; @@ -173,15 +174,15 @@ public boolean open(Config config) throws IOException { // grpc is the one other value the specification names, and the one a // copied collector config most often carries. Refused by name: the // server would otherwise start and send nothing anyone receives. - throw new IOException(PROTOCOL + " is '" + protocol + "'; this server exports " - + "OTLP over HTTP, so use http/protobuf or http/json, and point the " - + "endpoint at the collector's HTTP port (4318 by default, not 4317)"); + throw new IOException(PROTOCOL + " is '" + protocol + "'; use grpc, " + + "http/protobuf or http/json"); } String endpoint = config.get(TRACES_ENDPOINT); if (endpoint == null || endpoint.trim().length() == 0) { - String base = config.get(ENDPOINT, "http://localhost:4318").trim(); - endpoint = appendTracesPath(base); + String base = config.get(ENDPOINT, grpc ? "http://localhost:4317" + : "http://localhost:4318").trim(); + endpoint = grpc ? base : appendTracesPath(base); } endpoint = endpoint.trim(); if (!hasHttpAuthority(endpoint)) { @@ -208,6 +209,10 @@ public boolean open(Config config) throws IOException { seedIds(); exporter = new BatchExporter(endpoint, headers, protobuf, resource, queue, batch, delay, relayBytes * 4L); + if (grpc) { + // gRPC names the method itself, so only scheme, host and port are kept. + exporter.useGrpc(OtlpGrpc.target(endpoint)); + } if (config.getBoolean(RELAY, false)) { String configuredPath = config.get(RELAY_PATH, "/otel/v1/traces").trim(); String path = canonicalPath(configuredPath);