Documentation
¶
Overview ¶
Package parl handles inter-thread communication and controls parallelism
Logging of extected output is via Out(string, ...interface{}). Parl logging uses comma separator for numbers and is thread safe
Log(string, ...interface{}) always outputs to stderr. Console is the same intended to be used for command-line interactivity. SetDebug(true) appends code location
Info is active by default and outputs to stderr. SetSilent(true) removes this output. SetDebug(true) appends code location IsSilent deteremines if Info printing applies
Debug only prints if SetDebug(true) or the code location matches SetInfoRegexp(). The string matched for regular expression looks like: “github.com/haraldrudell/parl.FuncName” IsThisDebug determines if debug is active for the executing function
parl.D is intended for temporary printouts to be removed before check-in
parl provides generic recovery for goroutines and functions: capturing panics, annotating and storing errors and invoking an error handling function on errors:
func f() (err error) { defer parl.Recover(parl.Annotation(), &err, onError func(e error) { … }) …
Default error string: “Recover from panic in somePackage.someFunction: 'File not found'. For multiple errors, Recover uses error116 error lists, while Recover2 instead invokes onError multiple times
Parl is about 9,000 lines of Go code with first line written on November 21, 2018 ¶
On 3/16/2022 Parl was open-sourced under an ISC License
© 2020–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
© 2020–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) ISC License
Index ¶
- Constants
- func AddToPanic(panicValue interface{}, additionalErr error) (err error)
- func Annotation() (annotation string)
- func Console(format string, a ...interface{})
- func D(format string, a ...interface{})
- func Debug(format string, a ...interface{})
- func EnsureError(panicValue interface{}) (err error)
- func Errorf(format string, a ...interface{}) (err error)
- func HandleErrp(fn func(), errp *error)
- func HandlePanic(fn func()) (err error)
- func HandleParlError(fn func(), storeError func(error))
- func Info(format string, a ...interface{})
- func IsSilent() (isSilent bool)
- func IsThisDebug() bool
- func Log(format string, a ...interface{})
- func New(s string) error
- func NewDebouncer(d time.Duration, receiver ReceiverFunc, sender SenderFunc, ctx context.Context) (err error)
- func Out(format string, a ...interface{})
- func Recover(annotation string, errp *error, onError func(error))
- func Recover2(annotation string, errp *error, onError func(error))
- func SetDebug(debug bool)
- func SetRegexp(regExp string) (err error)
- func SetSilent(silent bool)
- func Sprintf(format string, a ...interface{}) string
- type AdbRequest
- type Adbette
- type Adbetter
- type AdressProvider
- type AndroidSerial
- type AndroidStatus
- type AtomicBool
- type Counter
- type CounterID
- type CounterValues
- type Counters
- type CountersFactory
- type Dent
- type Devicette
- type FSLocation
- type FanOut
- type FanProc
- type FanThunk
- type History
- type HistoryFactory
- type Moderator
- type OnceChan
- type Password
- type ReceiverFunc
- type SenderFunc
- type SerialDo
- type SerialDoEvent
- type SerialDoFunc
- type ServerFactory
- type Serverette
- type ServeretteFactory
- type SkeletonDevice
- type Statuser
- type StatuserFactory
- type Timer
- type Tracer
- type TracerFactory
- type TracerRecord
- type TracerTaskID
- type Trackerette
- type TriggeringChan
- type Value
- type WaitGroup
Constants ¶
const ( Rfc3339s = "2006-01-02 15:04:05-07:00" Rfc3339ms = "2006-01-02 15:04:05.999-07:00" Rfc3339us = "2006-01-02 15:04:05.999999-07:00" Rfc3339ns = "2006-01-02 15:04:05.999999999-07:00" Rfc3339sz = "2006-01-02T15:04:05Z" Rfc3339msz = "2006-01-02T15:04:05.999Z" Rfc3339usz = "2006-01-02T15:04:05.999999Z" Rfc3339nsz = "2006-01-02T15:04:05.999999999Z" )
const ( SerialDoReady = 0 + iota SerialDoLaunch // from idle, now time SerialDoPending // queued up invocation, request time SerialDoPendingLaunch // launch of pending invocation, request time SerialDoIdle // busy since )
Variables ¶
This section is empty.
Functions ¶
func AddToPanic ¶
func Annotation ¶
func Annotation() (annotation string)
func Console ¶
func Console(format string, a ...interface{})
Console always print intended for command-line interactivity if debug is enabled, code location is appended
func D ¶
func D(format string, a ...interface{})
D prints to stderr with code location Thread safe. D is meant for temporary output intended to be removed before check-in
func Debug ¶
func Debug(format string, a ...interface{})
Debug outputs only if debug is configured or the code location package matches regexp
func EnsureError ¶
func EnsureError(panicValue interface{}) (err error)
func Errorf ¶
parl.Errorf offers stack traces and other rich error feattues of packages perrors and errorglue
func HandleErrp ¶ added in v0.2.2
func HandleErrp(fn func(), errp *error)
HandleErrp recovers from panics when executing fn. A panic is stored at errp using error116.AppendError()
func HandlePanic ¶
func HandlePanic(fn func()) (err error)
HandlePanic recovers from panics when executing fn. A panic is returned in err
func HandleParlError ¶ added in v0.2.2
func HandleParlError(fn func(), storeError func(error))
HandleErrp recovers from panics when executing fn. A panic is provided to the storeError function. storeError can be the thread-safe error116.ParlError.AddErrorProc()
func Info ¶
func Info(format string, a ...interface{})
Info prints unless silence has been configured with SetSilence(true) IsSilent deteremines the state of silence if debug is enabled, code location is appended
func IsThisDebug ¶
func IsThisDebug() bool
IsThisDebug returns whether debug logging is configured for the executing function
func Log ¶
func Log(format string, a ...interface{})
Log invocations always print if debug is enabled, code location is appended
func New ¶
parl.New offers stack traces and other rich error feattues of packages perrors and errorglue
func NewDebouncer ¶
func NewDebouncer(d time.Duration, receiver ReceiverFunc, sender SenderFunc, ctx context.Context) (err error)
Debouncer debounces event streams of Value
func Recover ¶
Recover recovers from a panic invoking a function no more than once. If there is *errp does not hold an error and there is no panic, onError is not invoked. Otherwise, onError is invoked exactly once. *errp is updated with a possible panic.
func Recover2 ¶
Recover2 recovers from a panic and may invoke onError multiple times. onError is invoked if there is an error at *errp and on a possible panic. *errp is updated with a possible panic.
Types ¶
type AdbRequest ¶ added in v0.3.0
type AdbRequest string
type Adbette ¶ added in v0.3.0
type Adbette interface { // SendReadOkay sends a request to a remote adb endpoint. // if anything else than OKAY is received back from the // remote endpoint, err is non-nil. SendReadOkay(request AdbRequest) (err error) // ReadString reads utf-8 text up to 64 KiB-1 in length ReadString() (s string, err error) // ConnectToDevice sends a forwarding request to an adb // server to connect to one of its devices ConnectToDevice(serial AndroidSerial) (err error) // Shell executes a shell command on a device connected to the adb server Shell(command string, reader func(conn io.ReadWriteCloser) (err error)) (out string, err error) // TrackDevices orders a server to emit serial number as they become available TrackDevices() (err error) // Devices lists the currently online serials Devices() (serials []AndroidSerial, err error) // DeviceStati returns all available serials and their status // The two slices correspond and are of the same length DeviceStati() (serials []AndroidSerial, stati []AndroidStatus, err error) // Closer closes an adb connection, meant to be a deferred function Closer(errp *error) // SetSync chnages the protocol mode of an adb connection to sync SetSync() (err error) // LIST is a sync request that lists the entriues in a directory of an adb device LIST(remoteDir string, dentReceiver func(mode uint32, size uint32, time uint32, byts []byte) (err error)) (err error) // RECV fetches the contents of a file located on an adb device RECV(remotePath string, blobReceiver func(data []byte) (err error)) (err error) // CancelError is a value that a LIST or RECV callback routines can return to // cancel further invocations CancelError() (cancelError error) }
Adbette is a minimal implementation of the adb Android debug bridge protocol Adbette include both adb server and Android device functions
type Adbetter ¶ added in v0.3.0
type Adbetter interface {
NewConnection(address string, ctx context.Context) (conn Adbette, err error)
}
Adbetter is a factory instance for connections featuring Adbette
type AdressProvider ¶ added in v0.3.0
type AdressProvider interface {
DialAddress() (address string)
}
AdressProvider retrieves the address from an adb server or device so that custom devices can be created
type AndroidSerial ¶ added in v0.3.0
type AndroidSerial string
AndroidSerial uniquely identities an Anroid device. It is typically a string of a dozen or so 8-bit chanacters consisting of lower and upper case a-zA-Z0-9
type AndroidStatus ¶ added in v0.3.0
type AndroidStatus string
AndroidStatus indicates the current status of a device known to a Server or Serverette it is a short word of ANSII-set characters
const AndroidOnline AndroidStatus = "device"
AndroidOnline is the Android device status that indicates an online device
type AtomicBool ¶
type AtomicBool struct {
// contains filtered or unexported fields
}
AtomicBool is a thread-safe flag. AtomicBool requires no initialization
var isDone parl.AtomicBool if isDone.Set() // isDone was not set, but is set now … if !isDone.IsTrue() // isDone is not set
func (*AtomicBool) Clear ¶
func (ab *AtomicBool) Clear() (wasSet bool)
func (*AtomicBool) IsTrue ¶
func (ab *AtomicBool) IsTrue() (isTrue bool)
func (*AtomicBool) Set ¶
func (ab *AtomicBool) Set() (wasNotSet bool)
type Counter ¶ added in v0.3.0
type Counter interface { Inc() (counter Counter) Dec() (counter Counter) CounterValue(reset bool) (values CounterValues) }
type CounterValues ¶ added in v0.3.0
type CountersFactory ¶ added in v0.3.0
type Dent ¶ added in v0.3.0
type Dent interface { Name() (name string) // utf-8 Modified() (modified time.Time) // second precision, local time zone IsDir() (isDir bool) IsRegular() (isRegular bool) // ie.not directory or symlink Perm() (perm fs.FileMode) // 9 bits Unix permissions, directory and symlink Size() (size uint32) // limited to 4 GiB-1 }
Dent is the information returned by adb ls or LIST
type Devicette ¶ added in v0.3.0
type Devicette interface { SkeletonDevice // Serial() // Shell executes a shell command on the device. // The resulting socket can be obtained either using the reader callback, // which is a socket connection to the device, // or by collecting the out string. Shell(command string, reader func(conn io.ReadWriteCloser) (err error)) (out string, err error) // Pull copies a remote file or directory on the Android device to a local file system location. // the local file must not exist. Pull(remotePath, nearPath string) (err error) /* List has some peculiarities: If remoteDir is not an existing directory, an empty list is returned. Entries with insufficient permisions are ignored. Update: . and .. are removed, adb LIST ortherwise do return those. File mode: the only present type bits beyond 9-bit Unix permissions are symlink, regular file and directory. File size is limited to 4 GiB-1. Modification time resolution is second and range is confined to a 32-bit Unix timestamp. */ List(remoteDir string) (dFileInfo []Dent, err error) }
Devicette is a generic representation of an Android Devicette accessible via an AdbServer
type FSLocation ¶
type FSLocation interface {
Directory() (directory string)
}
type FanOut ¶
type FanOut struct { ErrCh chan error Results chan interface{} // contains filtered or unexported fields }
func (*FanOut) Do ¶
Do executes a procedure in a goroutine that has no result other than a possible non-nil error
type HistoryFactory ¶ added in v0.3.0
type Moderator ¶
type Moderator struct {
// contains filtered or unexported fields
}
Moderator invokes functions at a limited level of parallelism. It is a ticketing system
m := NewModerator(20, ctx) m.Do(func() (err error) { // waiting here for a ticket // got a ticket! … return or panic // ticket automatically returned m.String() → waiting: 2(20)
func NewModerator ¶
NewModerator creates a new Moderator used to limit parallelism
func (*Moderator) Do ¶
Do calls fn limited by the moderator’s parallelism. If the moderator is shut down, ErrModeratorShutdown is returned
type OnceChan ¶ added in v0.3.0
type OnceChan struct {
// contains filtered or unexported fields
}
OnceChan is a semaphore implementing the Context with Cancel interface. Whenever a context is required for cancellation, a OnceChan can be used in its place. Unlike context, OnceChan requires no initialization. Similar to Context, OnceChan can be waited on like a channel using Done(). OnceChan can be inspected using IsDone() or Err(). OnceChan is cancelled using .Cancel()
var semaphore OnceChan go func() { <-onceChan.Done() }() … semaphore.Cancel() … semaphore.IsDone()
type ReceiverFunc ¶
type ReceiverFunc func(c <-chan time.Time, done <-chan struct{}) (which TriggeringChan, value Value)
ReceiverFunc takes two channels, listens to them and a typed channel, returns what channel triggered and a possible untyped value
type SenderFunc ¶
type SenderFunc func([]Value)
SenderFunc takes an untyped value, type asserts and sends on a typed channel
type SerialDo ¶
type SerialDo struct { ErrCh chan error ID string Wg sync.WaitGroup // contains filtered or unexported fields }
serialdo invokes method in sequence
func NewSerialDo ¶
func NewSerialDo(thunk func(), eventReceiver SerialDoFunc, ctx context.Context) (sdo *SerialDo)
NewSerialDo SerialDo. errors on sdo.ErrCh
type SerialDoEvent ¶
type SerialDoEvent uint8
type SerialDoFunc ¶
type SerialDoFunc func(SerialDoEvent, *SerialDo, *time.Time)
type ServerFactory ¶ added in v0.3.0
type ServerFactory interface { // Adb connects to an adb adb Android Debug Bridge server on a specified tcp socket Adb(address string, ctx context.Context) (server Serverette) // AdbLocalhost connects to an adb Android Debug Bridge server on the local computer AdbLocalhost(ctx context.Context) (server Serverette) }
ServerFactory describes how AdbServer objects are obtained. Such servers may use duifferent protocol implementations from Adbette
type Serverette ¶ added in v0.3.0
type Serverette interface { // DeviceSerialList lists serials for the currently online Android devices DeviceSerialList() (serials []AndroidSerial, err error) // DeviceForSerial obtains AdbDevice for a serial. // The device instance can execute additional device functions. // Devicette can connect to the device similarly to how the server implementation // connects to trhe adb Android Debug Bridge server DeviceForSerial(serial AndroidSerial) (android SkeletonDevice, err error) // TrackDevices emits serial numbers for devices that come online. // serials are sent on the serials channel. // if err is non-nil, set-up of failed. // The errs channel closes when watching stops // Watching is stopped by calling cancel function or when the server’s context terminates TrackDevices() (tracker Trackerette, err error) }
Serverette is a generic representation of an adb server running on a host.
As of Android 12, Android Debug Bridge version 1.0.41 Version 32.0.0-8006631 has the following commands are supported: devices connect disconnect pair forward ppp reverse mdns push pull sync shell emu install install-multiple install-multiple-package uninstall bugreport jdwp logcat disable-verity enable-verity keygen wait-for* get-state get-serialno get-devpath remount reboot sideload root unroot usb tcpip start-server kill-server reconnect attach detach
type ServeretteFactory ¶ added in v0.3.0
type ServeretteFactory interface { // Adb connects to an adb adb Android Debug Bridge server on a specified tcp socket. // address is a string default "localhost:5037" and default port ":5037". // adbetter is a factory for Adbette connections. Adb(address string, adbetter Adbetter, ctx context.Context) (server Serverette) }
ServeretteFactory is a Server connection factory for Adbette implementations
type SkeletonDevice ¶ added in v0.3.0
type SkeletonDevice interface { // Serial returns the device serial number Serial() (serial AndroidSerial) }
SkeletonDevice respresents a minimal adb protocol level connection to an Android device via an adb server. A SkeletonDevice may also be an AddressProvider. // An address and an AndroidSerial is all required to make an Adbette connection
type StatuserFactory ¶ added in v0.3.0
type Timer ¶
type Timer struct { Label string // contains filtered or unexported fields }
Timer is a simple request timer
type Tracer ¶ added in v0.3.0
type Tracer interface { Assign(threadID goid.ThreadID, task TracerTaskID) (tracer Tracer) Record(threadID goid.ThreadID, text string) (tracer Tracer) Records(clear bool) (records map[TracerTaskID][]TracerRecord) }
type TracerFactory ¶ added in v0.3.0
type TracerFactory interface {
NewTracer() (tracer Tracer)
}
type TracerRecord ¶ added in v0.3.0
type TracerTaskID ¶ added in v0.3.0
type TracerTaskID string
type Trackerette ¶ added in v0.3.0
type Trackerette interface { // Serials emit serial number as online devices become available Serials() (serials <-chan AndroidSerial) // Errs is available once Serials close. It returns any errors Errs() (err error) // Cancel shuts down the Tracker Cancel() }
Trackerette represents a server connection emitting device serial numbers
type TriggeringChan ¶
type TriggeringChan uint8
const ( TimerCh TriggeringChan = iota DoneCh ValueCh )
type WaitGroup ¶ added in v0.3.0
parl.WaitGroup is like a sync.Waitgroup that can be inspected. The Waiting method returns the number of threads waited for. parl.WaitGroup requires no initialization.
var wg parl.WaitGroup wg.Add(1) … wg.Waiting()
func (*WaitGroup) NoneWaiting ¶ added in v0.3.0
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
cmd
|
|
parl
parl.go demonstrate usage of the parl package, a go library for command-line utilities and concurrency
|
parl.go demonstrate usage of the parl package, a go library for command-line utilities and concurrency |
Package errorglue contains helful declarations that are not important
|
Package errorglue contains helful declarations that are not important |
Package ev provides standardized goroutine management events contain thread completions, failures and any type of data items.
|
Package ev provides standardized goroutine management events contain thread completions, failures and any type of data items. |
Package evx contains declarations not essential to event handling
|
Package evx contains declarations not essential to event handling |
Package mains contains functions for implementing a service or command-line utility
|
Package mains contains functions for implementing a service or command-line utility |
omaps
module
|
|
Package parlca provides a self-signed certificate authority
|
Package parlca provides a self-signed certificate authority |
Package parlp provides portable computer process information
|
Package parlp provides portable computer process information |
Package error116 enrichens error values with string data, stack traces, associated errors, less severe warnings, thread-safe containers and comprehensive error string representations.
|
Package error116 enrichens error values with string data, stack traces, associated errors, less severe warnings, thread-safe containers and comprehensive error string representations. |
Package pfs provides file-system related functions Package pfs provides file-system related functions © 2020–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
|
Package pfs provides file-system related functions Package pfs provides file-system related functions © 2020–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) |
Package parlnet provides IP-related functions with few dependencies beyond the net package
|
Package parlnet provides IP-related functions with few dependencies beyond the net package |
Package parlos provides simplified functions related to the os package
|
Package parlos provides simplified functions related to the os package |
process
module
|
|
Package progress provides printable progress reporting for multi-threaded operations
|
Package progress provides printable progress reporting for multi-threaded operations |
Package pruntime provides an interface to the Go standard library’s runtime package using only serializable simple types Stack traces and code locations have several formats: codeLocation := pruntime.NewCodeLocation(0) codeLocation.Base() // package and type → mypackage.(*MyType).MyFunc codeLocation.PackFunc() // very brief → mypackage.MyFunc codeLocation.Name(): // function name only → MyFunc codeLocation.Short() // line, no package path → mypackage.(*MyType).MyFunc-myfile.go:19 codeLocation.Long() // uniquely identifiable → codeberg.org/haraldrudell/mypackage.(*MyType).MyFunc-myfile.go:19 codeLocation.Full() // everything → codeberg.org/haraldrudell/mypackage.(*MyType).MyFunc-/fs/mypackage/myfile.go:19 codeLocation.String() // two lines → "codeberg.org/haraldrudell/mypackage.(*MyType).MyFunc\n /fs/mypackage/myfile.go:19" Stack can determine where a goroutine was created and whether this is the main thread pruntime.GoRoutineID() → 1 pruntime.NewStack(0).Creator.Short() → main.main-pruntime.go:30 fmt.Println(pruntime.NewStack(0).IsMainThread) → true pruntime.NewStack(0).Frames[0].Args → (0x104c12c60?)
|
Package pruntime provides an interface to the Go standard library’s runtime package using only serializable simple types Stack traces and code locations have several formats: codeLocation := pruntime.NewCodeLocation(0) codeLocation.Base() // package and type → mypackage.(*MyType).MyFunc codeLocation.PackFunc() // very brief → mypackage.MyFunc codeLocation.Name(): // function name only → MyFunc codeLocation.Short() // line, no package path → mypackage.(*MyType).MyFunc-myfile.go:19 codeLocation.Long() // uniquely identifiable → codeberg.org/haraldrudell/mypackage.(*MyType).MyFunc-myfile.go:19 codeLocation.Full() // everything → codeberg.org/haraldrudell/mypackage.(*MyType).MyFunc-/fs/mypackage/myfile.go:19 codeLocation.String() // two lines → "codeberg.org/haraldrudell/mypackage.(*MyType).MyFunc\n /fs/mypackage/myfile.go:19" Stack can determine where a goroutine was created and whether this is the main thread pruntime.GoRoutineID() → 1 pruntime.NewStack(0).Creator.Short() → main.main-pruntime.go:30 fmt.Println(pruntime.NewStack(0).IsMainThread) → true pruntime.NewStack(0).Frames[0].Args → (0x104c12c60?) |
Package sqldb interfaces database/sql
|
Package sqldb interfaces database/sql |
Package parltime provides time utility functions
|
Package parltime provides time utility functions |
Package sqlite wraps modernc.org/sqlite
|
Package sqlite wraps modernc.org/sqlite |
sqliter
module
|
|
Package ghandi interfaces Android devices Package ghandi interfaces Android devices Package ghandi interfaces Android devices Package threadprof provide profiling of threading
|
Package ghandi interfaces Android devices Package ghandi interfaces Android devices Package ghandi interfaces Android devices Package threadprof provide profiling of threading |
watchfs
module
|
|
yaml
module
|
|
yamler
module
|