Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move over to the official bazel_worker implementation #68

Merged
merged 3 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions MODULE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ bazel_dep(name = "rules_jvm_external", version = "5.3")
bazel_dep(name = "rules_kotlin", version = "2.1.0")
bazel_dep(name = "bazel_skylib", version = "1.7.1")
bazel_dep(name = "platforms", version = "0.0.8")
bazel_dep(name = "bazel_worker_api", version = "0.0.4")
bazel_dep(name = "bazel_worker_java", version = "0.0.4")

bazel_dep(name = "aspect_bazel_lib", version = "2.11.0", dev_dependency = True)
bazel_dep(name = "buildifier_prebuilt", version = "8.0.0", dev_dependency = True)
Expand All @@ -25,11 +27,9 @@ maven.install(
"org.assertj:assertj-core:3.24.2",
"junit:junit:4.13.2",
# Worker Dependencies
# TODO(bencodes) Remove these and use the worker impl. that Bazel defines internally
"com.squareup.moshi:moshi:1.15.0",
"com.squareup.moshi:moshi-kotlin:1.15.0",
"com.squareup.okio:okio-jvm:3.6.0",
"io.reactivex.rxjava3:rxjava:3.1.8",
"com.google.protobuf:protobuf-java:4.29.0",
"com.google.protobuf:protobuf-java-util:4.29.0",
# Args Parsing
"com.xenomachina:kotlin-argparser:2.0.7",
# Lint Dependencies
"com.android.tools.lint:lint:31.3.0-alpha09",
Expand Down
686 changes: 244 additions & 442 deletions maven_install.json

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion rules/impl.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,6 @@ def _run_android_lint(
execution_requirements = {
"supports-workers": "1",
"supports-multiplex-workers": "1",
"requires-worker-protocol": "json",
},
env = {
# https://googlesamples.github.io/android-custom-lint-rules/usage/variables.md.html
Expand Down
8 changes: 3 additions & 5 deletions src/worker/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ kt_jvm_library(
srcs = glob(["*.kt"]),
visibility = ["//visibility:public"],
deps = [
"@rules_android_lint_deps//:com_squareup_moshi_moshi",
"@rules_android_lint_deps//:com_squareup_moshi_moshi_kotlin",
"@rules_android_lint_deps//:com_squareup_okio_okio_jvm",
"@rules_android_lint_deps//:io_reactivex_rxjava3_rxjava",
"@rules_android_lint_deps//:org_reactivestreams_reactive_streams",
"@bazel_worker_java//:worker_protocol_java_proto",
"@bazel_worker_java//src/main/java/com/google/devtools/build/lib/worker:work_request_handlers",
"@rules_android_lint_deps//:com_google_protobuf_protobuf_java",
],
)

Expand Down
134 changes: 23 additions & 111 deletions src/worker/PersistentWorker.kt
Original file line number Diff line number Diff line change
@@ -1,125 +1,37 @@
package com.rules.android.lint.worker

import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.schedulers.Schedulers
import java.io.BufferedOutputStream
import java.io.ByteArrayOutputStream
import com.google.devtools.build.lib.worker.ProtoWorkerMessageProcessor
import com.google.devtools.build.lib.worker.WorkRequestHandler
import java.io.IOException
import java.io.PrintStream
import java.time.Duration

internal class PersistentWorker(
/**
* WorkerIO instance wrapping the standard output streams
*/
private val workerIO: WorkerIO,
/**
* Rxjava Scheduler to execute work requests on.
*/
private val scheduler: Scheduler,
/**
* Instance of CpuTimeBasedGcScheduler that will run periodically
*/
private val persistentWorkerCpuTimeBasedGcScheduler: PersistentWorkerCpuTimeBasedGcScheduler,
/**
* Instance of CpuTimeBasedGcScheduler that will run periodically
*/
private val workRequestProcessor: Worker.WorkerMessageProcessor,
/**
* Instance of CpuTimeBasedGcScheduler that will run periodically
*/
private val workerWorkRequestCallback: Worker.WorkRequestCallback,
) : Worker {
constructor(
workerMessageProcessor: Worker.WorkRequestCallback,
) : this(
workerIO = WorkerIO(),
scheduler = Schedulers.io(),
persistentWorkerCpuTimeBasedGcScheduler = PersistentWorkerCpuTimeBasedGcScheduler(),
workRequestProcessor =
WorkerJsonMessageProcessor(
System.`in`,
System.out,
),
workerWorkRequestCallback = workerMessageProcessor,
)

/**
* Initiate the worker and begin processing work requests
*/
override fun processRequests(): Int {
return workerIO.use { io ->
// Start by redirecting the system streams so that nothing
// corrupts the streams that the worker uses
io.redirectSystemStreams()
val realStdErr: PrintStream = System.err

// Process requests as they come in using RxJava
Flowable
.create(
{ emitter ->
while (!emitter.isCancelled) {
try {
val request: WorkRequest = workRequestProcessor.readWorkRequest()
emitter.onNext(request)
} catch (e: IOException) {
emitter.onError(e)
}
}
},
BackpressureStrategy.BUFFER,
).subscribeOn(scheduler)
.parallel()
.runOn(scheduler)
// Execute the work and map the result to a work response
.map { request -> return@map this.respondToRequest(request) }
// Run the garbage collector periodically so that we are a good responsible worker
.doOnNext { persistentWorkerCpuTimeBasedGcScheduler.maybePerformGc() }
.doOnError { it.printStackTrace() }
.sequential()
.observeOn(scheduler)
.blockingSubscribe { response ->
workRequestProcessor.writeWorkResponse(response)
}
return@use 0
try {
val workerHandler: WorkRequestHandler =
WorkRequestHandler
.WorkRequestHandlerBuilder(
WorkRequestHandler.WorkRequestCallback { request, pw ->
return@WorkRequestCallback workerWorkRequestCallback.processWorkRequest(
request.argumentsList.toList(),
System.err,
)
},
realStdErr,
ProtoWorkerMessageProcessor(System.`in`, System.out),
).setCpuUsageBeforeGc(Duration.ofSeconds(10))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I ask what the purpose of setting this is and why you chose 10 seconds specifically?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copied this from the usages within Bazel core and their examples.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good, the PR looks good to me from my perspective.

.build()
workerHandler.processRequests()
} catch (e: IOException) {
e.printStackTrace(realStdErr)
return 1
}
}

private fun respondToRequest(request: WorkRequest): WorkResponse {
ByteArrayOutputStream().use { baos ->
// Create a print stream that the execution can write logs to
val printStream = PrintStream(BufferedOutputStream(ByteArrayOutputStream()))
var exitCode: Int
try {
// Sanity check the work request arguments
val arguments =
requireNotNull(request.arguments) {
"Request with id ${request.requestId} " +
"does not have arguments!"
}
require(arguments.isNotEmpty()) {
"Request with id ${request.requestId} " +
"does not have arguments!"
}
exitCode = workerWorkRequestCallback.processWorkRequest(arguments, printStream)
} catch (e: Exception) {
e.printStackTrace(printStream)
exitCode = 1
} finally {
printStream.flush()
}

val output =
arrayOf(baos.toString())
.asSequence()
.map { it.trim() }
.filter { it.isNotEmpty() }
.joinToString("\n")
return WorkResponse(
exitCode = exitCode,
output = output,
requestId = request.requestId,
)
}
return 0
}
}
41 changes: 0 additions & 41 deletions src/worker/PersistentWorkerCpuTimeBasedGcScheduler.kt

This file was deleted.

16 changes: 0 additions & 16 deletions src/worker/WorkRequest.kt

This file was deleted.

21 changes: 0 additions & 21 deletions src/worker/WorkResponse.kt

This file was deleted.

9 changes: 0 additions & 9 deletions src/worker/Worker.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.rules.android.lint.worker

import java.io.IOException
import java.io.PrintStream

interface Worker {
Expand All @@ -16,14 +15,6 @@ interface Worker {
): Int
}

interface WorkerMessageProcessor {
@Throws(IOException::class)
fun readWorkRequest(): WorkRequest

@Throws(IOException::class)
fun writeWorkResponse(workResponse: WorkResponse)
}

companion object {
/**
* Creates the appropriate worker instance using the provided worker arguments.
Expand Down
19 changes: 0 additions & 19 deletions src/worker/WorkerIO.kt

This file was deleted.

38 changes: 0 additions & 38 deletions src/worker/WorkerJsonMessageProcessor.kt

This file was deleted.

Loading
Loading